克隆"子阵列"对象数组(对象深度嵌套)

时间:2016-10-13 06:45:44

标签: javascript arrays json object clone

问题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"}]
}]

2 个答案:

答案 0 :(得分:0)

为什么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);

正如您所看到的,编辑foo上的b也会在a上对其进行更改,因为两个数组都包含指向相同对象的指针。

这就是你需要JSON.parse(JSON.stringify())

的原因

答案 1 :(得分:-1)

Array.slice()不进行深度复制,因此不适合多维数组。

当一个真值作为初始参数传递时,jQuery的extend方法会执行深层复制。

// Deep copy
var newArray = jQuery.extend(true, [], oldArray);

类似的帖子here