为了在JavaScript中复制数组:下面哪个使用更快?
片的方法
var dup_array = original_array.slice();
For循环
for(var i = 0, len = original_array.length; i < len; ++i)
dup_array[i] = original_array[i];
我知道这两种方法都只做一个浅拷贝:如果original_array包含对对象的引用,对象将不会被克隆,但只有引用将被复制,因此两个数组将有对相同对象的引用。
但这不是问题的关键。
我只是在问速度。
在ES6中,你可以简单地利用Spread语法。
例子:
let arr = ['a', 'b', 'c'];
let arr2 = [...arr];
请注意,展开操作符生成了一个全新的数组,因此修改一个不会影响另一个。
例子:
arr2.push('d') // becomes ['a', 'b', 'c', 'd']
console.log(arr) // while arr retains its values ['a', 'b', 'c']
看看:link。重点不是速度,而是舒适度。此外,正如你所看到的,你只能在原始类型上使用slice(0)。
要制作数组的独立副本,而不是对其引用的副本,可以使用数组切片方法。
例子:
To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.
var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();
To copy or clone an object :
function cloneObject(source) {
for (i in source) {
if (typeof source[i] == 'source') {
this[i] = new cloneObject(source[i]);
}
else{
this[i] = source[i];
}
}
}
var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};
var obj2= new cloneObject(obj1);
来源:链接
const arr = ['1', '2', '3'];
// Old way
const cloneArr = arr.slice();
// ES6 way
const cloneArrES6 = [...arr];
// But problem with 3rd approach is that if you are using muti-dimensional
// array, then only first level is copied
const nums = [
[1, 2],
[10],
];
const cloneNums = [...nums];
// Let's change the first item in the first nested item in our cloned array.
cloneNums[0][0] = '8';
console.log(cloneNums);
// [ [ '8', 2 ], [ 10 ], [ 300 ] ]
// NOOooo, the original is also affected
console.log(nums);
// [ [ '8', 2 ], [ 10 ], [ 300 ] ]
所以,为了避免这些情况的发生,使用
const arr = ['1', '2', '3'];
const cloneArr = Array.from(arr);