localStorage用法小总结

有时候会用,还是做一个总结吧。在Chrome浏览器的Console里面输入localStorage会出现下图:

2019-03-09T11:25:07.png

宿主(浏览器)提供的localStorage自带的方法,如下表所示:

名称作用
clear清空localStorage上存储的数据
getItem读取数据
hasOwnProperty检查localStorage上是否保存了变量x,需要传入x
key读取第i个数据的名字或称为键值(从0开始计数)
lengthlocalStorage存储变量的个数
propertyIsEnumerable用来检测属性是否属于某个对象的
removeItem删除某个具体变量
setItem存储数据
toLocaleString将(数组)转为本地字符串
valueOf获取所有存储的数据

清空localStorage

localStorage.clear()    // undefined    
localStorage            // Storage {length: 0}

存储数据

localStorage.setItem("name","hello") //存储名字为name值为caibin的变量
localStorage.name = "hello"; // 等价于上面的命令
localStorage // Storage {name: "hello", length: 1}

读取数据

localStorage.getItem("name") //hello,读取保存在localStorage对象里名为name的变量的值
localStorage.name // "hello"
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 // Storage {length: 0} 可以看到之前保存的name变量已经从localStorage里删除了

检查localStorage里是否保存某个变量

localStorage.hasOwnProperty('name') // true
localStorage.hasOwnProperty('sex')  // false

将数组转为本地字符串

var arr = ['aa','bb','cc']; // ["aa","bb","cc"]
localStorage.arr = arr //["aa","bb","cc"]
localStorage.arr.toLocaleString(); // "aa,bb,cc"

将JSON存储到localStorage里

var students = {
    xiaomin: {
        name: "xiaoming",
        grade: 1
    },
    teemo: {
        name: "teemo",
        grade: 3
    }
}

students = JSON.stringify(students);  //将JSON转为字符串存到变量里
console.log(students);
localStorage.setItem("students",students);//将变量存到localStorage里

var newStudents = localStorage.getItem("students");
newStudents = JSON.parse(students); //转为JSON
console.log(newStudents); // 打印出原先对象

仅有一条评论

  1. 回复

    虽然不知道说的是什么,但看起来好厉害的样子!

添加新评论