spread operator vs array.concat()

后端 未结 6 889
日久生厌
日久生厌 2020-12-01 04:00

What is the difference between spread operator and array.concat()

6条回答
  •  爱一瞬间的悲伤
    2020-12-01 04:46

    Well console.log(['one', 'two', 'three', 'four', 'five']) has the same result as well, so why use either here? :P

    In general you would use concat when you have two (or more) arrays from arbitrary sources, and you would use the spread syntax in the array literal if the additional elements that are always part of the array are known before. So if you would have an array literal with concat in your code, just go for spread syntax, and just use concat otherwise:

    [...a, ...b] // bad :-(
    a.concat(b) // good :-)
    
    [x, y].concat(a) // bad :-(
    [x, y, ...a]    // good :-)
    

    Also the two alternatives behave quite differently when dealing with non-array values.

提交回复
热议问题