setItem、getItem 基本操作
localStorage.setItem(Key, Value); // 設定 (Key Value 都是給字串)
localStorage.getItem(Key); // 選取 Key 抓出裡面的 Value
應用一:
透過 click 事件點擊手動新增 input 資料到 Local Storage。
應用二:
透過 click 事件點擊,呼叫 Local Storage 裡的值,並同步更新資料。
JSON.parse、JSON.stringify 編譯資料
儲存到 localstorage 裡的資料,或是從 localstorage 取出的資料,都是字串 string 格式。所以如果資料是一組陣列 array 或是 JSON 資料時,就必須經由 JSON.parse 解析,將其字串格式轉型(可利用 typeof 查詢目前格式類型)。如此一來才可以透過 array 的格式,操控陣列一樣去取出陣列裡的值。
1. 將 array 轉為 string
JSON.stringify();
2. 將 string 轉為 array
JSON.parse();
實際操作範例:
1. 未轉型
2. 有轉型
JSON.stringify 將要儲存的 Value 先轉成 字串,再將轉型後的字串 設定給 localStorage。(可以明顯看出 Application 結果的差異!)
3. 將 localStorage 內的 string 轉型成 array
轉形成 array 之後,便可取出陣列 [] 裡的值。