问题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 details -
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"}]
}]
如果JSON.parse(JSON.stringify())
是obj.slice(1, 3)
的结果,或者不是,为什么会有区别?这就是例1中发生的事情。
你得到obj.slice(1, 3)
,你得到相同的值,通过stringify/parse传递。
功能上类似于:
var foo = 'bar';
console.log(foo);
console.log(JSON.parse(JSON.stringify(foo)));
关于问题2:
易普.
obj.slice
不能单独用于克隆对象。它只是复制数组内容。在本例中,这些内容只是指向现有对象的指针:
var a = [{foo: 'bar'}, {x: 'y'}];
var b = a.slice(0,1)
console.log('B:', b);
b[0].foo = 'test';
console.log('After modification:');
console.log('A:', a);
console.log('B:', b);
可以看到,在b
上编辑foo
也会在a
上修改它,因为两个数组都包含指向相同对象的指针。
这就是为什么你需要JSON.parse(JSON.stringify())
。
Array.slice()不做深度复制,因此不适合多维数组。
jQuery的extend方法在传递一个真值作为初始参数时执行深度复制。
// Deep copy
var newArray = jQuery.extend(true, [], oldArray);
此处类似文章