数组对象在JavaScript中默认是引用类型。顾名思义、它是引用实际值,而自身不是实际值。由于这个原因,使用赋值操作(=)拷贝数组只是拷贝原始值的引用而不是实际的值。
在本文中,我们将介绍用JavaScript实际复制数组的5种方法。
1、扩展运算符
let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
console.log(clubs)
//Create a clone Es6 way
let clonedClubs = [...clubs]
console.log(clonedClubs)
2、for() 循环
let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
clonedClubs = [];
for (i = 0; i < clubs.length; i++) {
clonedClubs[i] = clubs[i];
}
console.log(clonedClubs)
3、Array map()
let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
cloning = (i) => i;
clonedClubs = clubs.map(cloning)
console.log(clonedClubs)
4、Array filter()
let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
clonedClubs = clubs.slice();
console.log(clonedClubs)
4、Array slice()
let clubs = ['Chelsea', 'Liverpool', 'Mancity', 'Real Madrid']
clonedClubs = clubs.slice();
console.log(clonedClubs)
网友评论