在浏览器中,可以使用全局的 structuredClone()
方法使用结构化克隆算法将给定的值进行深拷贝。以往 JavaScript 自带的拷贝,都是浅拷贝,而现在可以使用该方法进行深拷贝,而且支持循环引用。
参考文档:structuredClone() - Web API 接口参考 | MDN (mozilla.org)
该方法还支持把原始值中的可转移对象
转移到新对象,而不是把属性引用拷贝过去。 可转移对象与原始对象分离并附加到新对象;它们不可以在原始对象中访问被访问到。
方法使用:
const original = { name: "测试数据" };
original.itself = original;
const clone = structuredClone(original);
console.log(clone !== original); // true
console.log(clone.name === "测试数据"); // true
console.log(clone.itself === clone); // true
浏览器兼容性:
本文链接:
版权声明:自由转载-署名-非商业性使用 | CC BY-NC-SA 3.0 CN许可协议。
评论 (8)
当前评论模式:游客模式,系统将自动生成相关数据信息。《内容规范》你的账号名为:
z5svhI
游客
·
2 个月前
s4lyr2
游客
·
6 个月前
DEl_IG
@s4lyr2:ggggb
游客
·
5 个月前
DEl_IG
@DEl_IG:ggg
游客
·
5 个月前
DEl_IG
@DEl_IG:
游客
·
5 个月前
s4lyr2
游客
·
6 个月前
_Rq8BE
asd
游客
·
7 个月前
lol