JS数组深拷贝:structuredClone API的使用与兼容性

作者:木棉

时间:2026-11-30

浏览:558

使用 structuredClone() 进行深拷贝,它原生支持数组、对象及嵌套结构。

文章目录

JS数组深拷贝:structuredClone API的使用与兼容性

为什么选择 structuredClone

传统 JSON 序列化会丢失 Date、RegExp 等类型,而 structuredClone 是浏览器内置的标准化 API,能正确处理这些复杂类型。

JS数组深拷贝:structuredClone API的使用与兼容性

structuredClone 基于结构化克隆算法,支持循环引用检测。相比手动递归实现,它更安全且性能更优。适用于现代 Web 开发中需要完整保留数据类型的场景。

基础用法与代码示例

将包含日期和正则的数组传入 structuredClone,即可得到完全独立的副本。

JS数组深拷贝:structuredClone API的使用与兼容性

const original = [
  new Date('2023-01-01'),
  /test/g,
  { nested: true }
];

if (typeof structuredClone === 'function') {
  const cloned = structuredClone(original);
  console.log(cloned[0] instanceof Date); // true
  console.log(cloned[1].source); // "test"
  console.log(cloned !== original); // true
} else {
  console.error('Browser does not support structuredClone');
}

输出显示克隆后的数组元素类型保持正确,且与原数组内存地址不同。若环境不支持,控制台将报错提示。

确保在支持该 API 的环境中运行。对于不支持的环境,需考虑 Polyfill 或降级方案。

兼容性处理策略

检查 window.structuredClone 是否存在,若不存在则回退到 JSON.parse(JSON.stringify()) 或自定义函数。

注意降级方案的局限性:无法处理函数、undefined 及特殊对象。在生产环境中建议封装统一工具函数。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章