localStorage对象是HTML5的客户端存储持久化数据的方案,localStorage只能存储字符串;
如果需要存储复杂类型的数据例如:数组,对象,需要先使用JSON.stringify( array/object )方法将数组、对象转换为字符串形式,取出时再使用 JSON.parse( string )方法将字符串转换为对象、数组形式;
例子:
let data = {
"data": {
"id": 1,
"name": "jack",
}
};
localStorage.setItem('data', JSON.stringify(data));
let loc=JSON.parse(localStorage.getItem('data'))
console.log(loc);
let data = [
{
"father": {"id": 1,"name": "father",}
},
{
"son": {"id": 2,"name": "son",}
}
];
localStorage.setItem('data', JSON.stringify(data));
let loc = JSON.parse(localStorage.getItem('data'))
console.log(loc);