localStorage和sessionStorage的总结
localStorage:没有时间限制的数据存储
API:
1.localStorage.setItem('name','wangwei')/localStorage.name='wangwei'存储数据
2.localStorage.clear()清除所有存储
3.localStorage.getItem('name')/localStorage.name读取数据
4.localStorage.length获取个数
5.localStorage.valueOf()获取存储的所有数据
6.localStorage.key(0)获取某个下表的属性名
7.localStorage.removeItem("name")删除某个属性
8.localStorage.hasOwnProperty('name')检查是否存在某个属性
9.localStorage.arr.toLocaleString()将存储的数组转换为本地字符串
eg:
var arr = ['aa','bb','cc']; // ["aa","bb","cc"]
localStorage.arr = arr //["aa","bb","cc"]
localStorage.arr.toLocaleString(); // "aa,bb,cc"
"aa,bb,cc"
10.将json数据存储在本地
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); // 打印出原先对象
eg:统计用户打开该页面次数
if(localStorage.count){
localStorage.count=Number(localStorage.count)+1
}else {
localStorage.count=1
}
11.这里我们通过调用 localStorage
来访问一个 Storage
对象。首先,使用 !localStorage.getItem('bgcolor')
测试本地存储中是否包含该数据项。如果包含,则运行 setStyles()
函数,该函数使用 localStorage.getItem()
来获取数据项,并使用这些值更新页面样式。如果不包含,我们运行另一个函数 populateStorage()
,该函数使用 localStorage.setItem()
设置数据项,然后运行setStyles()
if(!localStorage.getItem('bgcolor')) {
populateStorage();
} else {
setStyles();
}
function populateStorage() {
localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
localStorage.setItem('font', document.getElementById('font').value);
localStorage.setItem('image', document.getElementById('image').value);
setStyles();
}
function setStyles() {
var currentColor = localStorage.getItem('bgcolor');
var currentFont = localStorage.getItem('font');
var currentImage = localStorage.getItem('image');
document.getElementById('bgcolor').value = currentColor;
document.getElementById('font').value = currentFont;
document.getElementById('image').value = currentImage;
htmlElem.style.backgroundColor = '#' + currentColor;
pElem.style.fontFamily = currentFont;
imgElem.setAttribute('src', currentImage);
}
sessionStorage只要浏览器关闭,数据就会被清除
API和localStorage相似