localStorage:
是一种你不主动清除它,它会一直将存储数据存储在客户端的存储方式,即使你关闭了客户端(浏览器),属于本地持久层储存
sessionStorage:
用于本地存储一个会话(session)中的数据,一旦会话关闭,那么数据会消失,比如刷新。
localStorage与sessionStorage具有相同的API,以下方法都可以用于sessionStorage
localStorage存储方法
localStorage.name ='vanida;
localStorage["name"]='vanida';
localStorage.setItem("name","vanida");
//这三种设置值方式是一样的;
localStorage获取值方法 var name = localStorage["name"]
var name= localStorage.name
var name= localStorage.getItem("name");
//这三种获取值方式是一样的;
localStorage清除特定值方法
//清除name的值
localStorage.removeItem("name");localStorage.name='';
localStorage清除所有值方法
localStorage.clear()
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(localStorage.getItem("person"));
// {name: "vanida", sex: "girl", age: 25}
转自: