美文网首页
localStorage的使用

localStorage的使用

作者: 懒懒猫 | 来源:发表于2021-06-20 11:59 被阅读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"

相关文章

网友评论

      本文标题:localStorage的使用

      本文链接:https://www.haomeiwen.com/subject/xmnkyltx.html