将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相同的数组,而不是一个新的独立数组。如何复制阵列以获得两个独立的阵列?
当前回答
使用此项:
让oldArray=[1,2,3,4,5];let newArray=oldArray.slice();console.log({newArray});
基本上,slice()操作克隆数组并返回对新数组的引用。
还应注意:
对于引用、字符串和数字(而不是实际对象),slice()将对象引用复制到新数组中。原始数组和新数组都引用同一对象。如果引用的对象发生更改,则这些更改对新阵列和原始阵列都可见。
字符串和数字等基元是不可变的,因此不可能更改字符串或数字。
其他回答
我个人更喜欢这种方式:
JSON.parse(JSON.stringify( originalObject ));
丹,没必要耍花样。你所需要做的就是通过这样做复制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上看看这个。
您可以使用阵列排列。。。复制阵列。
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());
您需要了解要使用的阵列的复杂性,然后应用最佳解决方案(即➡️ 引用数组中的引用项)
当有很多答案时,您必须使用最佳实践来解决这个问题。
我建议您使用阵列排列…复制阵列。
var arr1=[‘a’,‘b’,‘c’];
var arr2=[…arr1];