[js] 模拟 localStorage 时如何实现过期时间功能
1.存储时记录下有效截止时间
2.取数据时判断是否超过有效时间,在有效期内则返回,不在则提示或返回空并且将其删除
class MyStorage {get(key) {const wrapValue = localStorage.getItem(key)if (wrapValue == null) {return undefined}const {value, expires} = JSON.parse(wrapValue)
- if ((expires != null && Date.now() < expires) || expires == null) {
+ if (!expires || Date.now() < expires) {return value}
-
+ localStorage.rmeoveItem(key)return undefined}set(key, value, period) {const wrapValue = { value };if (period != null) {wrapValue.expires = Date.now() + period;}localStorage.setItem(key, JSON.stringify(wrapValue));}
}
个人简介
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎发表自己的看法
主目录
与歌谣一起通关前端面试题