localSstorage cannot directly store objects, and can use the conversion of json.stringify and JSON.parse to achieve the goal.
json.stringify: Convert an object to a JSON string
JSON.parse: convert a JSON string to an object
function storageObj(obj) {
var Str = JSON.stringify(obj); //将对象序列化
localStorage.setItem("key", str);
};
var objBefor = {
a:1,
b:2
};
storageObj(objBefor);
var obj = JSON.parse(localStorage.getItem("key")); //将JSON字符串转化为对象
console.log(obj,typeof objAfter);//{a: 1, b: 2} "object"