关于localStorage和sessionStorage存储用法的一些细节说明

localStorage 和 sessionStorage 基本用法基本一致;localStorage需要会长时间保存,而sessionStorage会保存在当前对话框,会随着创库的关闭而被清除,

存储的数据格式必须是string;所以当localStorage.setItem(a,b)时,不管b为何种数据,在存储时都会被强制转化为string格式,进而在拿取getItem(a)时得到的永远是字符串,

但是在存储过程中如下细节需要注意:


1.存储数组时如果不处理,得到的是数组元素的字符串,

var arr=[1,2,3];
localStorage.setItem("temp",arr); 
console.log(typeof localStorage.getItem("temp"));
console.log(localStorage.getItem("temp"));

//得到结果
string;

1,2,3;

如果想得到数组,必须先再存储时将其字符串话

var arr=[1,2,3];
localStorage.setItem("temp",JSON.stringify(arr)); 
console.log(typeof localStorage.getItem("temp"));
console.log(localStorage.getItem("temp"));
//得到结果
string
[1,2,3]

此时虽然已经得到数组,但是是字符串形式的数组,业务中需要将其JSON.parse(),转换格式才能进一步利用

var arr=[1,2,3];
localStorage.setItem("temp",JSON.stringify(arr)); 
console.log(typeof localStorage.getItem("temp"));
console.log(localStorage.getItem("temp"));
console.log(JSON.parse(localStorage.getItem("temp")));
//得到结果
string
[1,2,3]//string
[1, 2, 3]//array

2.存储对象(包括JSON对象)时如果不处理,得到的是对象元素的字符串,

var obj = {"a": 1,"b": 2};
localStorage.setItem("temp2", obj);
console.log(typeof localStorage.getItem("temp2"));
console.log(localStorage.getItem("temp2"));
//得到结果
string
[object Object]//键值对形式的字符串,因此是obj

此时对于结果不管是用eval()还是JSON.parse(),都无法解析,如需业务中正常利用,必须在存储前将其字符串化,然后获取后再格式化

var obj={"a": 1,"b": 2};
localStorage.setItem("temp",JSON.stringify(obj)); 
console.log(typeof localStorage.getItem("temp"));
console.log(localStorage.getItem("temp"));

console.log(JSON.parse(localStorage.getItem("temp")));
console.log(typeof JSON.parse(localStorage.getItem("temp")));

//得到结果
string
{"a":1,"b":2}//string
{a: 1, b: 2}//obj
object

总结:正常业务中时,不管是数组还是JSON对象,为保证存储读取后能正常使用,最好存储前JSON.stringify()一下需要存储的数据

原文地址:https://www.cnblogs.com/yogic/p/9331019.html