localStorage 和 sessionStorage 的用法

其实提供的接口很简单,localStorage 和 sessionStorage 的用法是一样的。

  • 设置数据:setItem(name, value)

  • 获取数据:getItem(name)

  • 删除键值:removeItem(name)

  • 删除所有键值:clear()

例如:

localStorage.setItem('name', 'wenzhixin'); localStorage.getItem('name'); //'wenzhixin' localStorage.removeItem('name'); localStorage.clear(); 

当然,你也可以使用普通的对象用法:

localStorage.name = 'wenzhixin'; localStorage['name'] = 'wenzhixin'; localStorage.name; //'wenzhixin' localStorage['name']; //'wenzhixin' delete localStorage.name;//删除键值 delete localStorage['name'];//删除键值 

实际使用中,会先将数据转换为 JSON,作为字符存储,如:

localStorage[name] = JSON.stringify(value); //存储 JSON.parse(localStorage[name]); //读取



--------------------------------------

if(typeof(Storage)!=="undefined")
{
localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: " + localStorage.lastname;
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}

 

你可能感兴趣的:(localStorage 和 sessionStorage 的用法)