Web存储对象有localStorage和sessionStorage两种,它允许我们以键值对的形式在浏览器上保存数据。
相同点
属性 | 说明 |
---|---|
setItem(key, value) | 存储键值对 |
getItem(key) | 获取键的值 |
removeItem(key) | 删除指定键 |
clear | 删除所有数据 |
key(index) | 获取对应索引的键名 |
length | 存储键值对数据 |
特点:
if (window.localStorage) {
alert('该浏览器支持 localStorage');
} else {
alert('该浏览器不支持localStorage!!!');
}
写:有三种方式如下代码所示
删除键:localStorage.removeItem("你的key值")
全部清空:localStorage.clear()
// 三种写方法
localStorage.nick = "有勇气的牛排";
localStorage["uid"] = 1;
localStorage.setItem("lv", "9");
// 三种读方法
console.log(localStorage.nick)
console.log(localStorage["uid"])
console.log(localStorage.getItem("lv"))
// 通用删除
localStorage.removeItem("nick")
localStorage.removeItem("uid")
localStorage.removeItem("lv")
// delete 删除方法
// delete localStorage.nick
// 全部清除
// localStorage.clear()
// 读
console.log("---")
console.log(localStorage.nick)
console.log(localStorage["uid"])
console.log(localStorage.getItem("lv"))
console.log("---")
方法:key()
// 写
localStorage.nick = "有勇气的牛排";
localStorage["uid"] = 1;
localStorage.setItem("lv", "9");
// 遍历所有键值对
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key)
console.log(key + " : " + value)
// alert(`${key}: ${localStorage.getItem(key)}`);
}
// 存储json对象
localStorage.userinfo = JSON.stringify({uid: 1, nick: "有勇气的牛排"})
// 读取
let userinfo = JSON.parse(localStorage.userinfo)
console.log(userinfo.uid)
console.log(userinfo.nick)
使用方法同localStorage
,但是有如下不同:
请参考localStorage