为了在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包含对对象的引用,对象将不会被克隆,但只有引用将被复制,因此两个数组将有对相同对象的引用。 但这不是问题的关键。

我只是在问速度。


当前回答

记住.slice()对二维数组不起作用。你需要一个这样的函数:

function copy(array) {
  return array.map(function(arr) {
    return arr.slice();
  });
}

其他回答

在JavaScript中快速复制数组的方法:

第1集:

#2: array1copy = array1.slice(0);

#3: array1copy = array1.slice();

如果数组对象包含一些json不可序列化的内容(函数,Number。POSITIVE_INFINITY等)更好地使用

array1copy = JSON.parse(JSON.stringify(array1))

ECMAScript 2015的扩展操作符方式:

基本的例子:

var copyOfOldArray = [...oldArray]
var twoArraysBecomeOne = [...firstArray, ..seccondArray]

在浏览器控制台中尝试:

var oldArray = [1, 2, 3]
var copyOfOldArray = [...oldArray]
console.log(oldArray)
console.log(copyOfOldArray)

var firstArray = [5, 6, 7]
var seccondArray = ["a", "b", "c"]
var twoArraysBecomOne = [...firstArray, ...seccondArray]
console.log(twoArraysBecomOne);

参考文献

展开运算符的6大用途 传播的语法

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

看看: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);

来源:链接

它取决于数组的长度。如果数组长度<= 1,000,000,slice和concat方法花费的时间大致相同。但当你给出一个更大的范围时,concat方法胜出。

例如,试试下面的代码:

var original_array = [];
for(var i = 0; i < 10000000; i ++) {
    original_array.push( Math.floor(Math.random() * 1000000 + 1));
}

function a1() {
    var dup = [];
    var start = Date.now();
    dup = original_array.slice();
    var end = Date.now();
    console.log('slice method takes ' + (end - start) + ' ms');
}

function a2() {
    var dup = [];
    var start = Date.now();
    dup = original_array.concat([]);
    var end = Date.now();
    console.log('concat method takes ' + (end - start) + ' ms');
}

function a3() {
    var dup = [];
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup.push(original_array[i]);
    }
    var end = Date.now();
    console.log('for loop with push method takes ' + (end - start) + ' ms');
}

function a4() {
    var dup = [];
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup[i] = original_array[i];
    }
    var end = Date.now();
    console.log('for loop with = method takes ' + (end - start) + ' ms');
}

function a5() {
    var dup = new Array(original_array.length)
    var start = Date.now();
    for(var i = 0; i < original_array.length; i ++) {
        dup.push(original_array[i]);
    }
    var end = Date.now();
    console.log('for loop with = method and array constructor takes ' + (end - start) + ' ms');
}

a1();
a2();
a3();
a4();
a5();

如果您将original_array的长度设置为1,000,000,slice方法和concat方法大约需要相同的时间(3-4 ms,取决于随机数)。

如果将original_array的长度设置为10,000,000,则slice方法需要超过60 ms, concat方法需要超过20 ms。