HTML5本地存储的4个API

本地存储localStorage 和 sessionStorage 他们都有共同的API,他们的区别是localStorage生命周期是删除为止,sessionStorage是关闭浏览器页面就清除

  .setItem

   作用是添加数据到本地,写法为localStorage.setItem("key","value")

  .getItem

   作用是获取本地存储的数据,写法为localStorage.getItem("key") 

   若找不到指定的key值,则返回null

  .removeItem

   作用是清理指定数据,写法为localStorage.removeItem("key")

  .clear

   作用是清空本地所有数据,写法为localStorage.clear()

 

在存储的时候最好使用JSON.stringify()对要保存的值转换成JSON格式,读取的时候再使用JSON.parse()转换回来

posted @ 2021-10-31 19:04  逐云去  阅读(210)  评论(0)    收藏  举报