自制结构化数据保存库
constructor: prefix="" 【字符串】键名前缀,不得为default,也不得含有/。与Storage类(如localStorage)类似,但只能操作与构造时声明的前缀吻合的键值对,且有以下不同:
undefined;BigInt类;Date类;RegExp类;Set类(因为不会递归处理,所以所有的值都应为能被JSON.stringify和JSON.parse处理的值,否则将会抛出异常);Map类(同上原因,所有的键和值都应为能被JSON.stringify和JSON.parse处理的值,否则将会抛出异常);JSON.stringify和JSON.parse处理的值(同上原因)。LocalObjectStorage.plugins.transformations.add添加,该方法有四个参数:
type 【字符串】类型名,不得为undefined、bigint、date、set、map、regexp、JSON,也不得为之前添加过的类型名(即不得重复);match 【函数】判断值是否为本类型,接受值为第一参数,返回布尔值;encode 【函数】将值转化为字符串,接受值为第一参数,返回字符串;decode 【函数】将字符串转化为值,接受字符串为第一参数,返回值。{
type: "map",
match: (t) => t instanceof Map,
encode: (m) => JSON.stringify([...m.entries()]),
decode: (m) => new Map(JSON.parse(m)),
}
await mw.loader.using(["ext.gadget.LocalObjectStorage"]); // 重要!否则不会加载库
const localObjectStorage = new LocalObjectStorage("test");
localObjectStorage.setItem("test", new Date("2021-04-15T00:00:00Z"));
localObjectStorage.setItem("test2", /\/\d/);
localObjectStorage.getItem("test"); // => new Date("2021-04-15T00:00:00Z")
localObjectStorage.getItem("test2"); // => RegExp /\/\d/
localObjectStorage.removeItem("test");
localObjectStorage.length; // => 1
localObjectStorage.key(0); // => "test2"
localObjectStorage.clear();
localObjectStorage.length; // => 0