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

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

其他回答

丹,没必要耍花样。你所需要做的就是通过这样做复制arr1。

var arr1=[‘a’,‘b’,‘c’];var arr2=[];var arr2=新数组(arr1);arr2.推送('d');//现在,arr2=[['a','b','c'],d']console.log('arr1:');控制台日志(arr1);console.log('arr2:');控制台日志(arr2);//以下是诀窍:var arr3=[…arr1];arr3.推送('d');//现在,arr3=[‘a’,‘b’,‘c’,‘d’];console.log('arr3:');控制台日志(arr3);

现在arr1和arr2是存储在单独堆栈中的两个不同数组变量。在jsfiddle上看看这个。

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

// 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安慰

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

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

来源:此处

在我的特殊情况下,我需要确保阵列保持完整,所以这对我来说很有用:

// Empty array
arr1.length = 0;
// Add items from source array to target array
for (var i = 0; i < arr2.length; i++) {
    arr1.push(arr2[i]);
}