localstorage学习笔记
//写入数据
localStorage.setItem('name','lily');
//读出数据
console.log(localStorage.getItem('name'));//lily
//缓存数据的长度
console.log(localStorage.length);// 1
//读取存储在localStorage的所有数据
console.log(localStorage.valueOf());// Storage {name: "lily", length: 1}
// 读取第一条数据的变量名
console.log(localStorage.key(0));// name
//删除某个变量
localStorage.removeItem("name");
console.log(localStorage.getItem('name'));// null
//检查localStorage里是否保存某个变量
localStorage.hasOwnProperty('name');// true
console.log(localStorage.hasOwnProperty('name'));// false
localStorage.hasOwnProperty('sex');// false
console.log(localStorage.hasOwnProperty('sex'))//false
//将数组转为本地字符串
vararr= ['aa','bb','cc'];// ["aa","bb","cc"]
localStorage.arr=arr;//["aa","bb","cc"]
//localStorage.setItem('arr',arr);
console.log(localStorage.getItem('arr'));
localStorage.arr.toLocaleString();// "aa,bb,cc"
console.log('=====>'+localStorage.arr.toLocaleString());
//将json存储到localstorage里
varstudents= {
xiaomin: {
name:"xiaoming",
grade:1
},
teemo: {
name:"teemo",
grade:3
}
};
students=JSON.stringify(students);//将JSON转为字符串存到变量里
console.log(students);
localStorage.setItem("students",students);//将变量存到localStorage里
varnewStudents=localStorage.getItem("students");
newStudents=JSON.parse(students);//转为JSON
console.log(newStudents);// 打印出原先对象