牛骨文教育服务平台(让学习变的简单)
博文笔记

html5本地存储localStorage 存储json对象存储格式问题

创建时间:2016-05-28 投稿人: 浏览次数:4627
localStorage.setItem(att)会自动将att存储成字符串形式,如:
var arr=[1,2,3];localStorage.setItem("temp",arr);typeof localStorage.getItem("temp");会返回StringlocalStorage.getItem("temp");会返回1,2,3

但值得注意的是,localStorage.setItem()却不会自动将Json对象转成字符串形式,如:
var obj={"a":1,"b":2];localStorage.setItem("temp2",obj);typeof localStorage.getItem("temp2");也会返回StringlocalStorage.getItem("temp");却返回[object Object]

用localStorage.setItem()正确存储json对象方法是:存储前先用JSON.stringify()方法将json对象转换成字符串形式,如:
var obj={"a":1,"b":2};obj=JSON.stringify(obj);localStorage.setItem("temp2",obj);typeof localStorage.getItem("temp2");返回StringlocalStorage.getItem("temp2");返回字符串格式:{"a":1,"b":2}

后续要操作该json对象,自然得将之前存储的json字符串先转成json对象再进行操作,如:
obj=JSON.parse(localStorage.getItem("temp2"));

操作完,存储信息前,记得再转换下格式:obj=JSON.stringify(obj); 另外:localStorage.getItem(att),若att未定义该语句会返回null值,而不是undefined
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。