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

后端 未结 22 1494
佛祖请我去吃肉
佛祖请我去吃肉 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:46

    There is a much cleaner solution:

    var srcArray = [1, 2, 3];
    var clonedArray = srcArray.length === 1 ? [srcArray[0]] : Array.apply(this, srcArray);
    

    The length check is required, because the Array constructor behaves differently when it is called with exactly one argument.

提交回复
热议问题