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

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

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


当前回答

如果要创建对象或数组的新副本,必须显式复制对象或数组元素的财产,例如:

var arr1 = ['a','b','c'];
var arr2 = [];

for (var i=0; i < arr1.length; i++) {
   arr2[i] = arr1[i];
}

您可以在Google上搜索有关不可变原始值和可变对象引用的更多信息。

其他回答

使用jQuery深度复制可以如下所示:

var arr2 = $.extend(true, [], arr1);

如果您在ECMAScript 6环境中,使用Spread Operator,您可以这样做:

var arr1=[‘a’,‘b’,‘c’];var arr2=[…arr1]//复制arr1arr2.推('d');控制台日志(arr1)控制台日志(arr2)<script src=“http://www.wzvang.com/snippet/ignore_this_file.js“></script>

以下是其他几种复制方法:

常量数组=[1,2,3,4];const arrayCopy1=对象.值(数组);const arrayCopy2=对象赋值([],数组);const arrayCopy 3=array.map(i=>i);const arrayCopy4=数组.of(…Array);

我发现这种方法比较容易:

设arr=[1,2,3,4,5];让newArr=[…arr];console.log(newArr);

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

  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());

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