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

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

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


当前回答

我个人更喜欢这种方式:

JSON.parse(JSON.stringify( originalObject ));

其他回答

对于包含对象的ES6阵列

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

您可以使用阵列排列。。。复制阵列。

const itemsCopy=[…items];

此外,如果要创建一个新数组,现有数组是其中的一部分:

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];

现在所有主流浏览器都支持数组排列,但如果您需要更旧的支持,请使用typescript或babel并编译到ES5。

有关点差的更多信息

正如我们在Javascript中所知道的那样,数组和对象都是通过引用的,但是我们可以用什么方法复制数组而不改变后面的原始数组呢?

这里有几种方法:

假设我们在您的代码中有这个数组:

var arr = [1, 2, 3, 4, 5];

1) 在函数中循环数组并返回一个新数组,如下所示:

 function newArr(arr) {
      var i=0, res = [];
      while(i<arr.length){
       res.push(arr[i]);
        i++;
       }
   return res;
 }

2) 使用slice方法,slice用于对数组的一部分进行切片,它将在不接触原始数组的情况下对数组的某些部分进行切片。在切片中,如果不指定数组的开始和结束,它将对整个数组进行切片,并基本上制作数组的完整副本,因此我们可以很容易地说:

var arr2 = arr.slice(); // make a copy of the original array

3) 还有contact方法,这是用于合并两个数组,但我们可以只指定其中一个数组,然后这基本上会复制新接触数组中的值:

var arr2 = arr.concat();

4) 另外,不建议使用stringify和parse方法,但这是复制Array和Objects的一种简单方法:

var arr2 = JSON.parse(JSON.stringify(arr));

5) Array.from方法,这不受广泛支持,使用前请检查不同浏览器中的支持:

const arr2 = Array.from(arr);

6) ECMA6方式,也不完全支持,但babelJs可以帮助您,如果您想转换:

const arr2 = [...arr];

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

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

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

来源:此处

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

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

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