将JavaScript中的数组复制到另一个数组时:

var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d');  //Now, arr1 = ['a','b','c','d']

我意识到arr2指的是与arr1相同的数组,而不是一个新的独立数组。如何复制阵列以获得两个独立的阵列?


当前回答

在研究之后,我发现一个干净的方法可以是:

  const arr1 = [['item 1-1', 'item 1-2'], ['item 2-1', 'item 2-2'], ['item 3-1', 'item 3-2']];

  /**
   * Using Spread operator, it will create a new array with no reference to the first level.
   * 
   * Since, the items are not primitive, they get their own references. It means that any change on them,
   * it will be still reflected on the original object (aka arr1).
   */
  const arr2 = [...arr1];

  /**
   * Using Array.prototype.map() in conjunction Array.prototype.slice() will ensure:
   * - The first level is not a reference to the original array.
   * - In the second level, the items are forced (via slice()) to be created as new ones, so there is not reference to the original items
   */
  const arr3 = arr1.map(item => item.slice());

您需要了解要使用的阵列的复杂性,然后应用最佳解决方案(即➡️ 引用数组中的引用项)

其他回答

let a = [1,2,3];

现在,您可以执行以下任一操作来创建阵列的副本。

let b = Array.from(a); 

OR

let b = [...a];

OR

let b = new Array(...a); 

OR

let b = a.slice(); 

OR

let b = a.map(e => e);

现在,如果我改变一个,

a.push(5); 

那么,a是[1,2,3,5],但b仍然是[1,3,3],因为它有不同的引用。

但我认为,在上述所有方法中,Array.from都更好,并且主要用于复制数组。

这是最新推出的Array.from,但不幸的是,截至本文撰写之时,它仅在最新的Firefox版本(32及更高版本)上受支持。它可以简单地使用如下:

var arr1 = [1, 2, 3];
console.log(Array.from(arr1)); // Logs: [1, 2, 3]

参考:此处

或者Array.prototype.map可以与标识函数一起使用:

function identity(param)
{
    return param;
}

var arr1 = [1, 2, 3],
    clone = arr1.map(identity);

参考:此处

制作多维数组/对象的副本:

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;
}

感谢詹姆斯·帕多尔西担任这一职务。

来源:此处

当有很多答案时,您必须使用最佳实践来解决这个问题。

我建议您使用阵列排列…复制阵列。

var arr1=[‘a’,‘b’,‘c’];

var arr2=[…arr1];

重要的

这里的大多数答案适用于特定情况。

如果您不关心深度/嵌套对象和道具,请使用(ES6):

let clonedArray=[…array]

但如果要进行深度克隆,请改用以下方法:

let cloneArray=JSON.parse(JSON.stringify(数组))*

*函数在使用stringify时不会被保存(序列化),如果没有它们,您将得到结果。


对于lodash用户:

let clonedArray=_.clone(数组)文档

and

let cloneArray=_.cloneDeep(数组)文档