webStorage之两种存储方式

171 阅读1分钟
webStorage统称
1.一般支持5MB的大小(不同浏览器不同)
2.浏览器端通过window.sessionStorage/window.locaStorage属性来实现本地存储机制

localStorage特点:
    1.关闭浏览器不会消失
    2.调用api或清空缓存
    3.如果获取不到value那么返回值会是null JSON.parse(null)的结果依然是null

sessionStorage特点:
    1.关闭浏览器不会清空
localStorage
写法:
let obj = {name:'张三',age:18}; // 写入自动会调用toString 写入就会变成[Object,Object]

// 写入
localStorage.setItem('person',JSON.stringfy(obj)); // JSON.stringfy把对象变字符串再存入

// 读取 
localStorage.getItem('person'); // 是一个字符串 所以需要JSON.parse解析一下变成对象
console.log(JSON.parse(localStorage.getItem('person'))); 

// 删除
localStorage.removeItem('person'); 

// 清空
localStorage.clear(); 

// 读取不出来的东西是null JSON.parse(null); // null
sessionStorage 会话
写法:
let obj = {name:'张三',age:18}; // 写入自动会调用toString 写入就会变成[Object,Object]

// 写入
sessionStorage.setItem('person',JSON.stringfy(obj)); // JSON.stringfy把对象变字符串再存入

// 读取 
sessionStorage.getItem('person'); // 是一个字符串 所以需要JSON.parse解析一下变成对象
console.log(JSON.parse(localStorage.getItem('person'))); 

// 删除
sessionStorage.removeItem('person'); 

// 清空
sessionStorage.clear(); 

// 读取不出来的东西是null JSON.parse(null); // null