spread syntax vs slice method

前端 未结 5 2204
终归单人心
终归单人心 2020-12-29 07:23

I was trying to understand what is the difference between spread syntax vs slice method in the following approach.

suppose I want to make an actual copy of an array,

5条回答
  •  轮回少年
    2020-12-29 07:52

    Those two methods aren’t actually equivalent though. Slice is a function on Array.prototype and is aware of the array’s implementation. It will create a very efficient deep copy. More importantly though, .slice() will preserve the sparseness information of your array.

    In contrast, [...Array] will simply create a new array from an iterable view of your existing array. Not necessarily as efficient.

    Try this:

    var a = [];
    a.length = 3;
    console.log("slice:", a.slice());
    console.log("spread:", [...a]);
    

    With Chrome Browser developer console, I get these results:

    slice: (3) [empty × 3]
    spread: (3) [undefined, undefined, undefined]
    

    If your array is particularly huge+sparse, array.slice() will be exceptionally fast. [...array] will probably hang your browser.

提交回复
热议问题