参数列表中不允许使用多个剩余运算符?

Jen*_*Mok 1 javascript ecmascript-6

function unshift(array, ...int) {
  return [...int].concat(array);
}

function unshift(...array, ...int) {
  return [...int, ...array];
}
Run Code Online (Sandbox Code Playgroud)

第一个函数很好,但第二个函数不行,所以函数中不存在多个剩余参数之类的东西吗?

sfl*_*che 5

正确的。对除最后一个参数之外的任何参数使用 Rest 运算符都会生成SyntaxError.

这是有道理的......

参数上的 Rest 运算符告诉编译器获取所有剩余的参数。如果第一个参数有一个剩余运算符,它将获取所有参数,之后任何后续参数都将是undefined

因此,Rest 参数只能位于参数列表中的最后一个参数上。

使用示例

function foo(bar, ...baz) {
  console.log(bar);
  console.log(baz); 
}

foo(1, 2, 3, 4);
// 1
// [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

如果在某个奇怪的世界中,Rest 参数可能位于许多参数中的第一个,那么我们就会有这样的东西

// NOT VALID JS
function foo(...bar, baz) {
  console.log(bar);
  console.log(baz); 
}

foo(1, 2, 3, 4);
// [1, 2, 3, 4]
// undefined
Run Code Online (Sandbox Code Playgroud)

那有什么用呢……?

  • 你的第二个例子有一个合理的解释,即“bar”将是“[1,2,3]”,“baz”将是“4”。为什么不支持呢? (3认同)