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

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

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


当前回答

使用此项:

让oldArray=[1,2,3,4,5];let newArray=oldArray.slice();console.log({newArray});

基本上,slice()操作克隆数组并返回对新数组的引用。

还应注意:

对于引用、字符串和数字(而不是实际对象),slice()将对象引用复制到新数组中。原始数组和新数组都引用同一对象。如果引用的对象发生更改,则这些更改对新阵列和原始阵列都可见。

字符串和数字等基元是不可变的,因此不可能更改字符串或数字。

其他回答

这是最新推出的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);

参考:此处

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

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

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

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

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

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

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

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

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

以下是如何对可变深度的基元数组执行此操作:

// If a is array: 
//    then call cpArr(a) for each e;
//    else return a

const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
let dst = cpArr(src);

https://jsbin.com/xemazog/edit?js安慰