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

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

    In ES6, you can simply utilize the Spread syntax.

    Example:

    let arr = ['a', 'b', 'c'];
    let arr2 = [...arr];
    

    Please note that the spread operator generates a completely new array, so modifying one won't affect the other.

    Example:

    arr2.push('d') // becomes ['a', 'b', 'c', 'd']
    console.log(arr) // while arr retains its values ['a', 'b', 'c']
    

提交回复
热议问题