Local Storage

瀏覽器資料儲存

Chun
4 min readJun 11, 2020

什麼是 Local Storage ?

一種存放在瀏覽器本身的資料庫,把一些相關的資訊都給紀錄進去。

從 Chrome 開法者工具 Application 內可發現,除了 Local Storage,尚有 Session Storage 和 Cookies,這三個都是業界常會去實作的資料庫。

利用綁定網址的方式,將相關資料紀錄起來,即便關閉瀏覽器仍保存資料,除非運用 JavaScript 將資料刪除或利用瀏覽器內的刪除語法。

setItem、getItem 基本操作

localStorage.setItem(Key, Value); // 設定 (Key Value 都是給字串)
localStorage.getItem(Key); // 選取 Key 抓出裡面的 Value
Application 結果
console 結果

應用一:

透過 click 事件點擊手動新增 input 資料到 Local Storage。

Application 結果

應用二:

透過 click 事件點擊,呼叫 Local Storage 裡的值,並同步更新資料。

Application 結果

JSON.parse、JSON.stringify 編譯資料

儲存到 localstorage 裡的資料,或是從 localstorage 取出的資料,都是字串 string 格式。所以如果資料是一組陣列 array 或是 JSON 資料時,就必須經由 JSON.parse 解析,將其字串格式轉型(可利用 typeof 查詢目前格式類型)。如此一來才可以透過 array 的格式,操控陣列一樣去取出陣列裡的值。

1. 將 array 轉為 string

JSON.stringify();

2. 將 string 轉為 array

JSON.parse();

實際操作範例:

1. 未轉型

Application 結果
console 結果

2. 有轉型

JSON.stringify 將要儲存的 Value 先轉成 字串,再將轉型後的字串 設定給 localStorage。(可以明顯看出 Application 結果的差異!)

Application 結果
console 結果

3. 將 localStorage 內的 string 轉型成 array

轉形成 array 之後,便可取出陣列 [] 裡的值。

--

--

No responses yet