Skip to content

Instantly share code, notes, and snippets.

@jacob-lcs
Last active Jan 2, 2021
Embed
What would you like to do?
对 localstorage 进行封装,使用方法见 comment
let storage = window.localStorage;
/**
* 判断是否为 JSON 对象
* @param obj
* @returns {boolean}
*/
function isJSON(obj) {
obj = JSON.stringify(obj);
return /^\{[\s\S]*\}$/.test(obj);
}
function stringify(val) {
return val === undefined || typeof val === "function" ? val + '' : JSON.stringify(val);
}
function deserialize(value) {
if (typeof value !== 'string') {
return undefined;
}
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
function dealIncognito(storage) {
let _KEY = '_Is_Incognit',
_VALUE = 'yes';
try {
storage.setItem(_KEY, _VALUE)
} catch (e) {
// 浏览器对于存储数据的大小有限制,限制的大小普遍在 5M,超出则会报 Uncaught QuotaExceededError 错误
if (e.name === 'QuotaExceededError') {
let _nothing = function () {};
storage.__proto__ = {
setItem: _nothing,
getItem: _nothing,
removeItem: _nothing,
clear: _nothing
};
}
} finally {
if (storage.getItem(_KEY) === _VALUE) storage.removeItem(_KEY);
}
return storage;
}
storage = dealIncognito(storage);
function Store() {}
Store.prototype = {
// 设置字段值
set: function (key, val) {
if (key && !isJSON(key)) {
storage.setItem(key, stringify(val));
} else if (isJSON(key)) {
for (const a in key) this.set(a, key[a]);
}
return this;
},
// 获取字段值
get: function (key) {
// 如果获取 key 为空,则将 localstorage 转为 JSON 对象返回
if (!key) {
let ret = {};
this.forEach((key, val) => ret[key] = val);
return ret;
}
// 检查 localstorage 中是否含有 key 字段
if (key.charAt(0) === '?') {
return this.has(key.substr(1));
}
const args = arguments;
if (args.length > 1) {
const dt = {};
for (let i = 0, len = args.length; i < len; i++) {
const value = deserialize(storage.getItem(args[i]));
if (value) {
dt[args[i]] = value;
}
}
return dt;
}
return deserialize(storage.getItem(key));
},
// 清空 localstorage
clear: function () {
storage.clear();
return this;
},
// 移除 localstorage 中的 key 字段
remove: function (key) {
let val = this.get(key);
storage.removeItem(key);
return val;
},
// 检查 localstorage 是否有 key 字段
has: function (key) {
return ({}).hasOwnProperty.call(this.get(), key);
},
// 获取 localstorage 中的所有字段值
keys: function () {
let d = [];
this.forEach((k) => {
d.push(k);
});
return d;
},
// 相当与 Array 的 forEach 函数
forEach: function (callback) {
for (let i = 0, len = storage.length; i < len; i++) {
let key = storage.key(i);
callback(key, this.get(key));
}
return this;
},
// 搜索字段值包含 str 的项
search: function (str) {
let arr = this.keys(),
dt = {};
for (let i = 0, len = arr.length; i < len; i++) {
if (arr[i].indexOf(str) > -1) dt[arr[i]] = this.get(arr[i]);
}
return dt;
}
}
const LS = new Store()
export default LS
@jacob-lcs

This comment has been minimized.

Copy link
Owner Author

@jacob-lcs jacob-lcs commented Jan 2, 2021

引入

import LS from './LS';

API

  1. 设置字段值
LS.set(key: string, val: string | object)
LS.set(key: object)
  1. 获取字段值
LS.get() // 获取 localstorage 中的所有值
LS.get(key: string) // 获取某个字段值
  1. 清空 localstorage
LS.clear()
  1. 移除 localstorage 中的 key 字段
LS.remove(key: string)
  1. 检查 localstorage 是否有 key 字段
LS.has(key: string)
  1. 获取 localstorage 中的所有字段值
LS.keys()
  1. 相当与 Array 的 forEach 函数
LS.forEach(callback: () => {})
  1. 搜索字段值包含 str 的项
LS.search(str: string)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment