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

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

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


当前回答

只是在写:

arr2 = arr1.concat();

您正在使用第一个数组的副本生成新数组。请注意,这是将元素推入数组的一种功能方式。

如果您的代码基于ES6,您也可以使用扩展运算符:

arr2 = [...arr1];

其他回答

对于包含对象的ES6阵列

cloneArray(arr) {
    return arr.map(x => ({ ...x }));
}

快速示例:

如果数组中的元素是基元类型(字符串、数字等)

var arr1=[‘a’,‘b’,‘c’];//arr1和arr2是独立的,基本元素存储在//记忆中的不同位置var arr2=arr1.slice();arr2.推('d');console.log(arr1);//[“a”、“b”、“c”]console.log(arr2);//[“a”、“b”、“c”、“d”]

如果数组中的元素是对象文本,则另一个数组({},[])

var arr1=[{x:'a',y:'b'},[1,2],[3,4]];//arr1和arr2是独立的,引用的/地址存储在不同的//记忆中的位置。但这些参考文献/地址指向了一些共同的地方//在存储器中。var arr2=arr1.slice();arr2.pop();//好-不影响arr1 bcos,只有arr2中的地址是//删除的不是该地址所指向的数据arr2[0].x=“z”;//不正常-影响在公共区域进行的arr1 bcos更改//由arr1和arr2中的地址指示arr2[1][0]=9;//不正常-与上述原因相同console.log(arr1);//[{x:'z',y:'b'},[9,2],[3,4]]console.log(arr2);//[{x:'z',y:'b'},[9,2]]

解决方案2:逐元素深度复制

var arr1=[{x:'a',y:'b'},[1,2],[3,4]];arr2=JSON.parse(JSON.stringify(arr1));arr2.pop();//OK-不影响arr1arr2[0].x=“z”;//好-不影响arr1arr2[1][0]=9;//OK-不影响arr1console.log(arr1);//[{x:“a”,y:“b”},[1,2],[3,4]]console.log(arr2);//[{x:'z',y:'b'},[9,2]]

structuredClone是一种新的深度克隆方法。

structuredClone(value)
structuredClone(value, { transfer })

transfer是一个值可转移对象数组,它将被移动而不是克隆到返回的对象中。

你可能会发现它的算法很有趣。

从ES2015开始,

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

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