js历史记录本地存储localStorage方法
存储类型自定义,本文以数组类型存储
添加历史记录
localAdd(name,value){
let stu;
let stuStr;
if (`${name}` in localStorage){//检测搜索记录存在时
stu= JSON.parse(localStorage[name]);
for (let i = 0; i < stu.length; i++) {
if (value == stu[i]){
return
}
}
stu.push(value);
stuStr = JSON.stringify(stu);
localStorage[name] = stuStr;
}else {//不存在时
stu = [];//存储数据形式
stu.push(value);
stuStr = JSON.stringify(stu);
localStorage[name] = stuStr;
}
}
删除所有历史记录
localDelete(name){
if (localStorage.getItem(`${name}`) === null){
return
}else {
localStorage.removeItem(`${name}`);
}
}
删除单个历史记录
localDeleteOne(name,index){
let stu;
let stuStr;
if (`${name}` in localStorage){
stu= JSON.parse(localStorage[name]);
stu.splice(index, 1);
if (stu.length == 0) {
localStorage.removeItem(`${name}`);
} else {
stuStr = JSON.stringify(stu);
localStorage[name] = stuStr;
}
}
}