localStorage的使用

2021-06-20  本文已影响0人  懒懒猫

清空localStorage

localStorage.clear()  // undefined 

存储数据

localStorage.setItem("name","caibin") //存储名字为name值为caibin的变量

localStorage.name = "caibin"; // 等价于上面的命令

读取数据

localStorage.getItem("name") //caibin,读取保存在localStorage对象里名为name的变量的值

localStorage.name // "caibin"

localStorage.valueOf() //读取存储在localStorage上的所有数据

localStorage.key(0) // 读取第一条数据的变量名(键值)

//遍历并输出localStorage里存储的名字和值

for(var i=0; i<localStorage.length;i++){

  console.log('localStorage里存储的第'+i+'条数据的名字为:'+localStorage.key(i)+',值为:'+localStorage.getItem(localStorage.key(i)));

}

删除某个变量

localStorage.removeItem("name"); //undefined
检查localStorage里是否保存某个变量

将数组转为本地字符串

var arr = ['aa','bb','cc']; // ["aa","bb","cc"]

localStorage.arr = arr //["aa","bb","cc"]

localStorage.arr.toLocaleString(); // "aa,bb,cc"

上一篇 下一篇

猜你喜欢

热点阅读