【发布时间】:2017-02-22 04:02:19
【问题描述】:
问题 1. 我想知道为什么
JSON.parse(JSON.stringify(obj.slice(1, 3))) and
obj.slice(1,3)
给出与输出相同的嵌套对象数组,因为obj.slice(1,3) 不应该正确克隆嵌套对象?
问题 2. JSON.parse(JSON.stringify(obj.slice(1, 3))) 是深度克隆子阵列的正确方法吗?
obj 详细信息 -
var obj= [{ name: "wfwfwfw.)csdfsd",
tags: [ "dfbdf>>sfdfds", "fsdfsdf&fsfd" ],
newer: { first: "this'one", second: ["that>.one", "another.'one"], third: {something: "some/>fded", newthing: "ddasd..>sqw"} },
final: [ {gh: "ty/fgfg", hj: "rt((ssds"}, {gh: "dqqq...g", hj: "gnm))s"} ]
},
{ name: "wfwfwwwwwwfw.)csdfsd",
tags: [ "dfbdf>>sfdfds", "fsdfsdf&fsfd" ],
newer: { first: "this'one", second: ["that>.one", "another.'one"], third: {something: "some/>fded", newthing: "ddasd..>sqw"} },
final: [ {gh: "ty/fgfg", hj: "rt((ssds"}, {gh: "dqqq...g", hj: "gnm))s"}]
},
{ name: "aa.)csdfsd",
tags: [ "dfbdf>>sfdfds", "fsdfsdf&fsfd" ],
newer: { first: "this'one", second: ["that>.one", "another.'one"], third: {something: "some/>fded", newthing: "ddasd..>sqw"} },
final: [ {gh: "ty/fgfg", hj: "rt((ssds"}, {gh: "dqqq...g", hj: "gnm))s"}]
},
{ name: "nn.)csdfsd",
tags: [ "dfbdf>>sfdfds", "fsdfsdf&fsfd" ],
newer: { first: "this'one", second: ["that>.one", "another.'one"], third: {something: "some/>fded", newthing: "ddasd..>sqw"} },
final: [ {gh: "ty/fgfg", hj: "rt((ssds"}, {gh: "dqqq...g", hj: "gnm))s"}]
}]
【问题讨论】:
-
obj.slice(1,3)和JSON.parse(JSON.stringify(obj.slice(1, 3)))给出相同的输出,因为它们做的事情完全相同。到达那里需要更长的时间。 -
是不是意味着obj.slice(1,3)可以用于深度克隆对象?
-
没有。 slice 只是复制引用。
obj,slice返回的结果中的引用与obj中的引用相同。JSON.stringify从您的对象创建字符串,然后JSON.parse将字符串转换为具有相同结构的新对象。你得到相同的输出,因为它们是副本。没有办法区分它们(除了它们在内存中的地址不同,即使用 ===)
标签: javascript arrays json object clone