Try   HackMD

Local Storage 瀏覽器資料儲存

JavaScript 入門篇 - 學徒的試煉
上課筆記 加上個人詮釋與額外補充

基礎概念

我們可以將網頁的資料儲存在 Local Storage,在 Local Storage 上的資料會永久儲存,主動清除才會消失。可以應用在顯示查詢紀錄、最近瀏覽

範例程式碼

如何在開發者工具查看

F12 -> Application

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →


基本操作

setItem 設定 鍵/值 (key/Value)

var str = 'Bob' localStorage.setItem("myName", str);

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

getItem 取得 鍵/值 (key/Value)

console.log(localStorage.getItem("myName"));

編譯資料

Local Storage 只能儲存「字串」資料
直接給陣列,Local Storage 會自動轉為字串,但變成 "[object Object]",原本的資料就掰掰了

將 array 轉為 string

var schoolString = JSON.stringify(school); // "[{'teacher':'Peggy'}]"

將 string 轉回 array

從 Local Storage 取回資料都會是「字串」型式,先轉回 array 利於後續使用

var getDataAry = JSON.parse(getData);
tags: 六角學院 程式設計 Local Storage 筆記