localStorage存储方法

localStorage存储方法
localStorage.name = localStorage["name"]='vanida';
localStorage.setItem("name","vanida");//这三种设置值方式是一样的;
 
localStorage获取值方法
var name=localStorage.name = localStorage["name"] = localStorage.setItem("name");//这三种取值方式是一样的;
 
localStorage清值方法
localStorage.removeItem("name");或者localStorage.name='';//清除name的值
 

localStorage只能存储字符串,如果需要存储对象,首先要转化为字符串。利用JSON.stringify();
例子:
var person = {name:"vanida","sex":"girl","age":25};localStorage.setItem("person",JSON.stringify(person));
// localStorage.person="{"name":"vanida","sex":"girl","age":25}"


要特别注意JSON.stringify()中不要忘了“i”,stringify而不是stringfy。已经被坑了好几次!
然后取出person的对象你可以用JSON.parse();
例子:
person = JSON.parse(storage.getItem("person"));
// {name: "vanida", sex: "girl", age: 25}

 
 
posted @ 2017-03-24 14:18  英dan  阅读(1444)  评论(0编辑  收藏  举报