跳到主要内容

LocalStorage

一、认识


二、语法


2.1 获取

localStorage.getItem(key);

2.2 新增

localStorage.setItem(key,value);

2.3 删除

localStorage.removeItem(key);

2.4 清空

localStorage.clear();

三、特点


  • 容量: localStorage的容量上限为5M

  • 生命周期: localStorage** 持久存储

四、封装


class LocalStorage{
constructor(){
this.storage = window.localStorage;
}

setItem(key,value,expire){
const item = {
value,
expire: expire ? new Date().getTime() + expire : null
}
this.storage.setItem(key, JSON.stringify(item));
}

getItem(key){
const itemStr = this.storage.getItem(key);
if(itemStr){
const item = JSON.parse(itemStr);
if(!item.expire || new Date().getTime() < item.expire){
return item.value;
}else{
this.storage.removeItem(key);
}
}
return null;
}

removeItem(key){
this.storage.removeItem(key);
}

clear(){
this.storage.clear();
}
}

测试实例

const localStorage = new LocalStorage();

localStorage.setItem(1,'嘻嘻',6 * 1000);

console.log(localStorage.getItem(1))

setTimeout(()=>{
console.log(localStorage.getItem(1));
},8000);

参考资料


localStorage灵魂五问。 5M?? 10M !!!