Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

后端 未结 22 1553
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:10

In order to duplicate an array in JavaScript: which of the following is faster to use?

###Slice method

var dup_array = original_array.slice();
<         


        
22条回答
  •  無奈伤痛
    2020-11-22 02:40

    a.map(e => e) is another alternative for this job. As of today .map() is very fast (almost as fast as .slice(0)) in Firefox, but not in Chrome.

    On the other hand, if an array is multi-dimensional, since arrays are objects and objects are reference types, none of the slice or concat methods will be a cure... So one proper way of cloning an array is an invention of Array.prototype.clone() as follows.

    Array.prototype.clone = function(){
      return this.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] = "two";
    console.log(JSON.stringify(arr));
    console.log(JSON.stringify(brr));

提交回复
热议问题