Using spread operator multiple times in javascript?

前端 未结 3 1345
梦如初夏
梦如初夏 2020-11-27 06:44

Why can\'t spread operator be used multiple times?

let arr = [[[1, 2, 3]]];

console.log(arr); // Array [ Array[1] ]
console.log(...arr); // Array [ Array[3]         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 07:30

    Because ...arr isn't like a function that returns a value in normal scenarios (you can test this by just typing ...[[1,2,3]] in console, if ... operated like a normal function we would expect a return of [1 2 3]. For that reason you can't chain spreads. From MDN:

    The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

    Ergo, spreads need to happen within array literals, object literals (if using obj spread, which is ES7) or within function calls So you could do console.log(...[].concat(...arr))

提交回复
热议问题