Try   HackMD

Javascript Local storage

使用瀏覽器其實有空間可以讓我們將使用者輸入的資料暫時存放在儲存空間,方便我們將使用者的資料儲存,並提取使用。

瀏覽器儲存空間

localStorage:

可跨瀏覽器使用,資料永遠被儲存,使用者關掉網頁再打開,資料依然存在。

  • 缺點:
    • 容量只有5mb,需要有大量資料來運算時會不夠。
    • 資料儲存的格式 key 和 value 都只能接受字串,若儲存的資料非字串 — 陣列或物件 — 在儲存時會被轉成字串格式。

因為儲存的時候是以array的形式,在application 裡local storage顯現是物件,key跟value都是

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 →

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 →

  • 可以透過JSON.stringfy()方式,將資料轉換為 JSON 格式的字串;

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 →

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 →

  • 要取出資料時,再透過 JSON.parse() 方法,將資料轉換回原本的格式

seccsionStorage:

生命短,關掉網頁,儲存的資料就不見了。

儲存格式:

  1. 資料需要是以類似 JSON 的 Key-value pair 格式儲存
  2. key 和 value 皆需要為 字串

使用方式:

  1. setItem(儲存資料)
    透過setItem()指定物件的key & value,可以在web storage 物件,加入屬性或是修改設定的鍵與值。
localStorage.setItem(key, value)
seccsionStorage.setItem(key, value)
  1. getItem(參數)(提取資料)
    透過輸入參數- key值,可以得到相對應的鍵值。
localStorage.getItem(key)
seccsionStorage.getItem(key)
  1. removeItem()(移除資料)
    可以把指定的屬性,從storage物件移除。
localStorage.removeItem(key, value)
seccsionStorage.removeItem(key, value)
tags: javascript,JSON