持久性紀錄
特性 | cookie | localStorage | sessionStorage |
生命週期 |
可設定失效時間 預設是關閉瀏覽器後失效 |
除非被清除,否則永久保存 | 關閉頁面或瀏覽器後被清除 |
大小 | 4KB 左右 | 一般為 5MB | |
與 Server 溝通 |
每次都會攜帶在 HTTP 中,保存過多數據會帶來效能問題 |
僅在瀏覽器保存,不參與 Server 溝通 |
localStorage.setItem(key, value)
sessionStorage.setItem(key, value)
localStorage.setItem('name', 'david')
let students = [];
students.push({name: 'David', age: 18})
students.push({name: 'John', age: 20})
localStorage.setItem('students', students)
查看後顯示
[object Object],[object Object]
JSON.stringify()
修正
let students = [];
students.push({name: 'David', age: 18})
students.push({name: 'John', age: 20})
localStorage.setItem('students', JSON.stringify(students))
var person = {
name: 'David',
age: 18,
sayHi: function() { console.log('Hi') }
}
localStorage.setItem('person', JSON.stringify(person))
function 無法被序列化
localStorage.getItem(key)
sessionStorage.getItem(key)
取回 students
localStorage.getItem('students')
查看發現取回後是字串
JSON.parse(localStorage.getItem('students'))
localStorage.removeItem(key)
sessionStorage.removeItem(key)
刪除 students
localStorage.removeItem('students')