class storage {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage;
}
setItem(params = {}) {
if (params) {
let {
key,
value,
} = params;
let obj = {
time: new Date().getTime(),
type: typeof (value),
key: key,
value: value
};
this.storage.setItem(key, JSON.stringify(obj));
}
}
getItem(key) {
let params = this.storage.getItem(key);
if (params) {
params = JSON.parse(params);
return params.value;
}
}
removeItem(key) {
this.storage.removeItem(key);
}
clear() {
this.storage.clear();
}
len() {
return this.storage.length;
}
null(key) {
const val = this.storage.getItem(key);
if (!val) {
return "The current key value pair does not exist.";
}
let { value } = JSON.parse(val);
if (typeof value === 'boolean') {
return false
}
if (typeof value === 'number') {
return false
}
if (value instanceof Array) {
if (value.length == 0) return true
} else if (value instanceof Object) {
if (JSON.stringify(value) === '{}') return true
} else {
if (value == 'null' || value == null || value == 'undefined' || value == undefined || value == '') return true
return false
}
return false
}
}
const l = new storage();
const s = new storage(false);
//存
s.setItem({
key: "name",
value:
[
{ id: "1", color: "rbga(0,0,0,1)" },
{ id: "2", color: "rgba(255,255,255,1)" }
],
});
//取
const get=s.getItem("name");
console.log(get)
//删除
s.removeItem("name");
//清空
s.clear();
//长度
const length=s.len();
console.log(length)
//判空
const b = s.null("name");
console.log(b)
浏览器存储封装
于 2022-10-29 01:03:07 首次发布