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

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

            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 ] ]
    

    So, in order to avoid these scenarios to happen, use

            const arr = ['1', '2', '3'];
    
            const cloneArr = Array.from(arr);
    

提交回复
热议问题