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

我只是在问速度。


当前回答

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

其他回答

A.map (e => e)是这项工作的另一种选择。到目前为止,.map()在Firefox中非常快(几乎和.slice(0)一样快),但在Chrome中则不然。

另一方面,如果一个数组是多维的,因为数组是对象,对象是引用类型,没有一个slice或concat方法将是治愈…因此,克隆数组的一种正确方法是array .prototype.clone()的发明,如下所示。

Array.prototype.clone = function(){ 返回。map(e => Array.isArray(e) ?e.clone(): e); }; var arr =[1、2、3、4(1、2(1、2、3),4、5],6], BRR = arr.clone(); Brr [4][2][1] = " 2 "; console.log (JSON.stringify (arr)); console.log (JSON.stringify (brr));

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

来源:链接

克隆对象数组的最快方法是使用展开运算符

var clonedArray=[...originalArray]
or
var clonedArray = originalArray.slice(0); //with 0 index it's little bit faster than normal slice()

但是克隆数组中的对象仍然指向旧的内存位置。因此改变到clonedArray对象也会改变orignalArray。所以

var clonedArray = originalArray.map(({...ele}) => {return ele})

这不仅将创建新的数组,而且还将克隆对象。

免责声明,如果你正在使用嵌套对象,在这种情况下,展开操作符将工作为浅克隆。在这一点上最好使用

var clonedArray=JSON.parse(JSON.stringify(originalArray));

那我们的方式呢?

arr2 = [...arr1];

基准时间!

function log(data) { document.getElementById("log").textContent += data + "\n"; } benchmark = (() => { time_function = function(ms, f, num) { var z = 0; var t = new Date().getTime(); for (z = 0; ((new Date().getTime() - t) < ms); z++) f(num); return (z) } function clone1(arr) { return arr.slice(0); } function clone2(arr) { return [...arr] } function clone3(arr) { return [].concat(arr); } Array.prototype.clone = function() { return this.map(e => Array.isArray(e) ? e.clone() : e); }; function clone4(arr) { return arr.clone(); } function benchmark() { function compare(a, b) { if (a[1] > b[1]) { return -1; } if (a[1] < b[1]) { return 1; } return 0; } funcs = [clone1, clone2, clone3, clone4]; results = []; funcs.forEach((ff) => { console.log("Benchmarking: " + ff.name); var s = time_function(2500, ff, Array(1024)); results.push([ff, s]); console.log("Score: " + s); }) return results.sort(compare); } return benchmark; })() log("Starting benchmark...\n"); res = benchmark(); console.log("Winner: " + res[0][0].name + " !!!"); count = 1; res.forEach((r) => { log((count++) + ". " + r[0].name + " score: " + Math.floor(10000 * r[1] / res[0][1]) / 100 + ((count == 2) ? "% *winner*" : "% speed of winner.") + " (" + Math.round(r[1] * 100) / 100 + ")"); }); log("\nWinner code:\n"); log(res[0][0].toString()); <textarea rows="50" cols="80" style="font-size: 16; resize:none; border: none;" id="log"></textarea>

自单击按钮以来,基准测试将运行10秒。

我的结果:

Chrome (V8引擎):

1. clone1 score: 100% *winner* (4110764)
2. clone3 score: 74.32% speed of winner. (3055225)
3. clone2 score: 30.75% speed of winner. (1264182)
4. clone4 score: 21.96% speed of winner. (902929)

Firefox (SpiderMonkey Engine):

1. clone1 score: 100% *winner* (8448353)
2. clone3 score: 16.44% speed of winner. (1389241)
3. clone4 score: 5.69% speed of winner. (481162)
4. clone2 score: 2.27% speed of winner. (192433)

赢家代码:

function clone1(arr) {
    return arr.slice(0);
}

赢家引擎: SpiderMonkey (Mozilla Firefox)