JS - LocalStorage 基本應用

LocalStorage

儲存在瀏覽器內對於特定網頁的Local資料庫,關閉網頁、再次開啟網頁時仍可存取。 使用JS清除或者使用者於瀏覽器進行清除資料才會不見。

Image


基本語法: setItem() / getItem() / removeItem() / clear()

  • 儲存特定資料

      localStorage.setItem('key', value)
  • 取出特定資料

      localStorage.getItem('key')
  • 刪除特定資料

      localStorage.removeItem('key')
  • 清除所有資料

      localStorage.clear()

資料型態為字串

  • 儲存於 LocalStorage 的資料只能是字串,故:
    • 想存 Array 或 Object 時,必須先轉型為 String
    • 自 LocalStorage 取出的資料都是字串,必須轉型回來,才能對其操作 Array / Obj 方法
  • 轉字串 js JSON.stringify(el)
  • 字串轉回 Array / Obj js JSON.parse(el)

  • 查詢資料格式 js typeof(el)


[例1] 輸入名字儲存至 LocalStorage,並自 LocalStorage 內取值顯示於頁面

HTML

<p>Hi!<span class="showName"></span></p>
<label>Name</label>
<input class="name" type="text"/>
<button id="submit">Submit</button>

JavaScript

function saveName() {
    let dataName = document.querySelector('.name').value
    localStorage.setItem('userName', dataName)
}
  • 取 input 內容存到 localStorage
  • localStorage.setItem('key', value)

function showName() {
    let nameDom = document.querySelector('.showName')
    nameDom.innerHTML = localStorage.getItem('userName')
}
  • 從 LocalStorage 裡取值並顯示在指定的 DOM
  • localStorage.getItem('userName')

showName();
  • 一開始就先執行showName(輸入過一次,下次再瀏覽此網頁時也顯示名字)

let btnSubmit = document.querySelector('#submit')
btnSubmit.addEventListener('click', function () {
    saveName();
    showName();
})
  • 定義按鈕觸發事件:儲存輸入的名字、更新名字


[例2] 非字串資料存進與讀取

var classmate = [
    {
        01: 'Eudora',
        02: 'Amy',
        03: 'Betty'
    }
]
  1. 直接存進 LocalStorage 會變字串 [object object]

     localStorage.setItem('classmate': classmate)

    Image


  1. JSON.stringify轉為字串後再存才能正確存進資料

     localStorage.setItem('classmate', JSON.stringify(classmate))

    Image


  1. 直接取出時,資料是字串,需透過JSON.parse轉型回來,:

     typeof(localStorage.getItem('classmate'))              // > string
     typeof(JSON.parse(localStorage.getItem('classmate')))  // > object

參考資料