…每个对象在同一个数组中也有对其他对象的引用?

当我第一次想到这个问题的时候,我就想到了

var clonedNodesArray = nodesArray.clone()

并搜索如何在JavaScript中克隆对象的信息。我确实在Stack Overflow上找到了一个问题(同样由@JohnResig回答),他指出用jQuery你可以做到

var clonedNodesArray = jQuery.extend({}, nodesArray);

克隆对象。虽然我尝试了这个,但这只复制了数组中对象的引用。如果我

nodesArray[0].value = "red"
clonedNodesArray[0].value = "green"

nodesArray[0]和clonedNodesArray[0]的值将显示为“绿色”。然后我尝试了

var clonedNodesArray = jQuery.extend(true, {}, nodesArray);

它深度复制了一个对象,但我分别从Firebug和Opera Dragonfly得到了“太多递归”和“控制堆栈溢出”的消息。

你会怎么做?这是不应该做的事情吗?在JavaScript中是否有可重用的方法来做到这一点?


当前回答

下面的代码将递归地执行对象和数组的深度复制:

function deepCopy(obj) {
    if (Object.prototype.toString.call(obj) === '[object Array]') {
        var out = [], i = 0, len = obj.length;
        for ( ; i < len; i++ ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    if (typeof obj === 'object') {
        var out = {}, i;
        for ( i in obj ) {
            out[i] = arguments.callee(obj[i]);
        }
        return out;
    }
    return obj;
}

其他回答

person1 = {
    name: 'Naved',
    last: 'Khan',
    clothes: {
        jens: 5,
        shirts: 10
    }
};

person2 = {
    name: 'Naved',
    last: 'Khan'
};

// first way  shallow copy single lavel copy 
// const person3 = { ...person1 };

// secound way shallow copy single lavel copy
// const person3 = Object.assign({}, person1);

// third  way shallow copy single lavel copy but old 
// const person3 = {};
// for (let key in person1) {
//  person3[key] = person1[key];
// }

// deep copy with array and object best way
const person3 = JSON.parse(JSON.stringify(person1));

    person3.clothes.jens = 20;

console.log(person1);
console.log(person2);
console.log(person3);

使用structuredClone创建深度拷贝

在JavaScript中深度复制数组的现代方法是使用structuredClone:

array2 = structuredClone(array1);

然而,这个功能相对较新(Chrome 98, Firefox 94),目前只有大约85%的用户可以使用,所以它还没有准备好投入生产。

作为替代方案,您可以使用下面支持良好的基于json的解决方案之一。

使用JSON.parse创建深度副本

一个通用的解决方案,即在对象数组中考虑所有可能的对象可能是不可能的。 也就是说,如果数组包含具有json序列化内容的对象(没有函数,没有Number。POSITIVE_INFINITY等)一个以性能为代价避免循环的简单方法就是这种纯香草式的单行解决方案。

let clonedArray = JSON.parse(JSON.stringify(nodesArray))

总结一下下面的评论,这种方法的主要优点是它还克隆数组的内容,而不仅仅是数组本身。主要的缺点是它只能处理json序列化的内容,而且它的性能比spread方法慢30倍。

如果数组中有浅对象,并且IE6是可以接受的,那么更好的方法是将展开操作符与.map数组操作符结合使用。对于两层深的情况(如下面附录中的数组):

clonedArray = nodesArray.map(a => {return {...a}})

原因有两个:1)它的速度要快得多(参见下面的基准比较),而且它还允许数组中的任何有效对象。

*附件: 性能量化是基于克隆这个对象数组一百万次:

 [{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic1.jpg?raw=true', id: '1', isFavorite: false}, {url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic2.jpg?raw=true', id: '2', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic3.jpg?raw=true', id: '3', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic4.jpg?raw=true', id: '4', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic5.jpg?raw=true', id: '5', isFavorite: true},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic6.jpg?raw=true', id: '6', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic7.jpg?raw=true', id: '7', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic8.jpg?raw=true', id: '8', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic9.jpg?raw=true', id: '9', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic10.jpg?raw=true', id: '10', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic11.jpg?raw=true', id: '11', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic12.jpg?raw=true', id: '12', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic13.jpg?raw=true', id: '13', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic14.jpg?raw=true', id: '14', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic15.jpg?raw=true', id: '15', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic16.jpg?raw=true', id: '16', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic17.jpg?raw=true', id: '17', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic18.jpg?raw=true', id: '18', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic19.jpg?raw=true', id: '19', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic20.jpg?raw=true', id: '20', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic21.jpg?raw=true', id: '21', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic22.jpg?raw=true', id: '22', isFavorite: false},{url: 'https://github.com/bobziroll/scrimba-react-bootcamp-images/blob/master/pic23.jpg?raw=true', id: '23', isFavorite: false}]

使用:

let clonedArray = JSON.parse(JSON.stringify(nodesArray))

or:

clonedArray = nodesArray.map(a => {return {...a}})

map/spread方法每次传递花费0.000466毫秒,JSON。解析和JSON。Stringify 0.014771毫秒每传递

如何使用一个简单的递归函数来获得对象/数组的深层副本

const deepCopyFunction = (inObject) => { const deepCopyObject = Array.isArray(inObject) ?[]: {}; for (inObject中的const键){ if (typeof inObject[key] === 'object') { deepCopyFunction (inObject(例子)); } deepCopyObject[key] = inObject[key]; } 返回deepCopyObject; }

在JavaScript中,数组和对象复制会改变原始值,因此深度复制是解决这个问题的解决方案。

深度复制实际上意味着创建一个新数组并复制值,因为无论它发生什么都不会影响原始数组。

JSON。解析和JSON。Stringify是深度复制的最佳和简单的方法。JSON.stringify()方法将JavaScript值转换为JSON字符串。JSON.parse()方法解析JSON字符串,构造由字符串描述的JavaScript值或对象。

深克隆

let a = [{ x:{z:1} , y: 2}];
let b = JSON.parse(JSON.stringify(a));
b[0].x.z=0

console.log(JSON.stringify(a)); //[{"x":{"z":1},"y":2}]
console.log(JSON.stringify(b)); // [{"x":{"z":0},"y":2}]

更多细节:阅读这里

如果你只需要一个浅拷贝,一个非常简单的方法是:

new_array = old_array.slice(0);