文章目录

html5本地存储localStorage 存储json对象存储格式问题
localStorage.setItem(att)会自动将att存储成字符串形式,如:

1
2
3
4
var arr = [1,2,3];
localStorage.setItem("temp", arr);
typeof localStorage.getItem("temp"); // "string"
localStorage.getItem("temp"); //"1,2,3"

但值得注意的是,localStorage.setItem()却不会自动将Json对象转成字符串形式,如:

1
2
3
4
var obj = {"a": 1,"b": 2};
localStorage.setItem("temp2", obj);
typeof localStorage.getItem("temp2"); // "string"
localStorage.getItem("temp2"); // "[object Object]"

用localStorage.setItem()正确存储json对象方法是:存储前先用JSON.stringify()方法将json对象转换成字符串形式,如:

1
2
3
4
5
var obj = {"a": 1,"b": 2};
obj = JSON.stringify(obj);
localStorage.setItem("temp2", obj);
typeof localStorage.getItem("temp2"); // "string"
localStorage.getItem("temp2"); // "{"a":1,"b":2}"

后续要操作该json对象,自然得将之前存储的json字符串先转成json对象再进行操作,如:

1
obj = JSON.parse(localStorage.getItem("temp2")); //Object {a: 1, b: 2}

操作完,存储信息前,记得再转换下格式:obj=JSON.stringify(obj);

另外:localStorage.getItem(att),若att未定义该语句会返回null值,而不是undefined

文章目录