将JavaScript中的数组复制到另一个数组时:
var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']
我意识到arr2指的是与arr1相同的数组,而不是一个新的独立数组。如何复制阵列以获得两个独立的阵列?
将JavaScript中的数组复制到另一个数组时:
var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']
我意识到arr2指的是与arr1相同的数组,而不是一个新的独立数组。如何复制阵列以获得两个独立的阵列?
当前回答
对于包含对象的ES6阵列
cloneArray(arr) {
return arr.map(x => ({ ...x }));
}
其他回答
其中一些方法在处理简单的数据类型(如数字或字符串)时工作得很好,但当数组包含其他对象时,这些方法会失败。当我们试图将任何对象从一个数组传递到另一个数组时,它将作为引用传递,而不是对象。
在JavaScript文件中添加以下代码:
Object.prototype.clone = function() {
var newObj = (this instanceof Array) ? [] : {};
for (i in this) {
if (i == 'clone')
continue;
if (this[i] && typeof this[i] == "object") {
newObj[i] = this[i].clone();
}
else
newObj[i] = this[i]
} return newObj;
};
只需使用
var arr1 = ['val_1','val_2','val_3'];
var arr2 = arr1.clone()
这会奏效的。
只是在写:
arr2 = arr1.concat();
您正在使用第一个数组的副本生成新数组。请注意,这是将元素推入数组的一种功能方式。
如果您的代码基于ES6,您也可以使用扩展运算符:
arr2 = [...arr1];
当有很多答案时,您必须使用最佳实践来解决这个问题。
我建议您使用阵列排列…复制阵列。
var arr1=[‘a’,‘b’,‘c’];
var arr2=[…arr1];
您可以使用阵列排列。。。复制阵列。
const itemsCopy=[…items];
此外,如果要创建一个新数组,现有数组是其中的一部分:
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
现在所有主流浏览器都支持数组排列,但如果您需要更旧的支持,请使用typescript或babel并编译到ES5。
有关点差的更多信息
在研究之后,我发现一个干净的方法可以是:
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());
您需要了解要使用的阵列的复杂性,然后应用最佳解决方案(即➡️ 引用数组中的引用项)