(Local storage and session storage both store key-value pairs.
The main difference between local storage and session storage is that , after 关闭浏览器
the end , the key-value pairs stored in the session 会话存储
will be lost, and the local storage will not )
1. Local storage
localStorage.setItem('键', '值'); //本地存储键值对
//typeof 为object类型
let Name = localStorage.getItem('键') //在本地存储中获取键值对
console.log(Name) //输出值
//如果从不存在的本地存储中获取内容,则结果为 null
One limitation of local storage is that it stores arrays as strings, so we use JSON.stringify to store arrays in local storage.
let name = ['a', 'b', 'c']
localStorage.setItem('name1',JSON.stringify(name)); //将name以数组形式存储在name1中
Then we use to JSON.parse
get the array from local storage
console.log(JSON.parse(localStorage.getItem('name1')));
So we use: JSON.stringify : to set the array to a value in local storage. JSON.parse: Get an array from local storage. Used to localStorage.clear()
clear local storage. Use to localStorage.removeItem('键')
delete a specific key-value pair.
2. Session storage
// 存储键值对
sessionStorage.setItem('键', '值');
// 获取
sessionStorage.getItem('键');
// 存储数组
let name = ['a', 'b', 'c']
sessionStorage.setItem('name1',JSON.stringify(name));
// 获取数组
console.log(JSON.parse(sessionStorage.getItem('name1')));
// 清除会话存储
sessionStorage.clear()
// 清除特定键值对
sessionStorage.removeItem('键');