JS数组深拷贝:structuredClone API的使用与兼容性
作者:木棉时间:2026-11-30浏览:570
使用 structuredClone() 进行深拷贝,它原生支持数组、对象及嵌套结构。
为什么选择 structuredClone
传统 JSON 序列化会丢失 Date、RegExp 等类型,而 structuredClone 是浏览器内置的标准化 API,能正确处理这些复杂类型。
structuredClone 基于结构化克隆算法,支持循环引用检测。相比手动递归实现,它更安全且性能更优。适用于现代 Web 开发中需要完整保留数据类型的场景。
基础用法与代码示例
将包含日期和正则的数组传入 structuredClone,即可得到完全独立的副本。
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 及特殊对象。在生产环境中建议封装统一工具函数。
作者最新文章
ES6一行代码实现JS数组去除指定元素
2026-12-01
JS怎么判断数字是否为整数
2026-12-01
JS数组unshift方法详解:语法、返回值与原地修改特性
2026-12-01
Kotlin环境下Android与JS交互的最佳实践
2026-12-01
JS封装通用保留两位小数工具函数代码
2026-12-01

