结构化 Clone 多填充
具有再生能力和外型的可知序列器和去序列器 贾森 从 HTML 语言 标准本身.
- 支持类型
- 尚未支持: Blob、 文件、 文件列表、 图像比特地图、 图像数据或其他非 联合来文 类型但打入的数组在没有重大问题的情况下支持,但u/int8、u/int16和u/int32是唯一安全的上接(现在).
- 无法执行页:1
{transfer: []}选项可以被通过,但它被完全忽略.
- MDN 文档
- 序列器
- 减序器
串行值可以安全地被字符串为 贾森 以及去区域化 复活所有价值 甚至递归性 或比什么更复杂 贾森 允许.
实例
检查 100%的测试覆盖率 要知道更多的东西.
// as default export
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone({any: 'serializable'});
// as independent serializer/deserializer
import {serialize, deserialize} from '@ungap/structured-clone';
// the result can be stringified as JSON without issues
// even if there is recursive data, bigint values,
// typed arrays, and so on
const serialized = serialize({any: 'serializable'});
// the result will be a replica of the original object
const deserialized = deserialize(serialized);
全球多元填充
注意: 如果需要, 只有猴子补丁全局 。 这种多填充效果只是一个明确的导入: import structuredClone from "@ungap/structured-clone"
// Attach the polyfill as a Global function
import structuredClone from "@ungap/structured-clone";
if (!("structuredClone" in globalThis)) {
globalThis.structuredClone = structuredClone;
}
// Or don't monkey patch
import structuredClone from "@ungap/structured-clone"
// Just use it in the file
structuredClone()
说明: 不要将本模块默认导出直接附加到全局范围, 请设置一个条件性守护以检测本地执行 。 在全球各地实施 structuredClone() 指派到全局对象后,将产生无限循环 globalThis.structuredClone() 名为. 参见上面的例子,以安全的方式提供您项目中的多填充.
额外特性
结构化克隆算法和JSON之间没有中间地层:
- JSON对不兼容的价值观比较放松:它只是忽略了这些
- 结构化克隆在不兼容的价值观上是僵硬的,然而它却使得专门的例子无法重建,再加上它不提供任何帮助者,例如:
toJSON(),使有具体案例的序列化成为可能或更好
本单元专门 serialize 在可选附加参数中,导出要约 a 损失 属性,以避免在道路上找到不兼容类型(功能、符号.)时扔出,这样就可以在发送时减少对抛出错误的担心.
// as default export
import structuredClone from '@ungap/structured-clone';
const cloned = structuredClone(
{
method() {
// ignored, won't be cloned
},
special: Symbol('also ignored')
},
{
// avoid throwing
lossy: true,
// avoid throwing *and* looks for toJSON
json: true
}
);
行为也一样 贾森 当它涉及到 阵列,这样,不支持的值将因 null 占位符代替.
给杰森
若为 lossy 选项是不够的, json 将实际执行 lossy 检查 toJSON 用于分析对象的方法.
备选案文 json 出口将所有特性结合起来:
import {stringify, parse} from '@ungap/structured-clone/json';
parse(stringify({any: 'serializable'}));