寻梦旅人 2022-05-04 12:25:18
localstorage本身没有时间过期的功能,要是自己封装一个简单的localstorage功能的话,可以使用定时器去实现过期时间的功能,值得注意的是执行定时器后,到指定的时间,记得destroy定时器。
export class mockLocalstorage {
constructor() {
this.store = new Map(); // 记录存储数据
}
getItem(key) {
const stringKey = String(key);
if (this.store.has(stringKey)) {
return String(this.store.get(stringKey));
} else {
return null;
}
}
// time单位是小时
setItem(key, val, time = "undefined") {
let stime = null;
if (typeof time !== "number" && time !== "undefined") {
throw new Error("设置过期时间的基础单位是小时,请不要破坏规则!");
}
if (time !== "undefined") {
time = time * 60 * 60 * 1000; // h ---> ms
try {
let _this = this;
this.store.set(String(key), val);
// 设置定时器 定时清空垃圾数据
stime = setTimeout(() => {
_this.removeItem(key);
stime = null;
}, time);
} catch (e) {
stime = null;
throw new Error(e);
}
}
}
keys() {
return Object.keys(this.store);
}
removeItem(key) {
this.store.delete(String(key));
}
clear() {
this.store.clear();
}
get length() {
return this.store.size;
}
}
测试代码(vue代码)
let _this = this;
let time = null;
this.mockLocalstorage.setItem("name", "duya", 0.01);
console.log(this.mockLocalstorage.getItem("name")); // 测试mockLocalstorage duya
// 检测数据又没有清空
- 共 1 页
- 1
第 46 题:输出以下代码执行的结果并解释为什么?