最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple rest operators not allowed in parameter list? - Stack Overflow

programmeradmin4浏览0评论
function unshift(array, ...int) {
  return [...int].concat(array);
}

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

The first function is fine but not the second one, so there's no such thing as multiple rest argument in function?

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

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

The first function is fine but not the second one, so there's no such thing as multiple rest argument in function?

Share Improve this question edited Jun 11, 2017 at 5:22 sfletche 49.8k31 gold badges108 silver badges120 bronze badges asked Jun 11, 2017 at 4:49 Jenny MokJenny Mok 2,8049 gold badges33 silver badges62 bronze badges 2
  • 7 And what sense would it make? Where do you expect array to finish and int to start? – RaphaMex Commented Jun 11, 2017 at 4:52
  • 2 To be pedantic, this is not the "rest operator". It's "rest parameter syntax" or "rest parameter notation". – user663031 Commented Jun 11, 2017 at 5:44
Add a ment  | 

3 Answers 3

Reset to default 5

Correct. Using the Rest operator on any parameter but the last results in a SyntaxError.

And it makes sense...

The Rest operator on the parameter tells the piler to grab all remaining arguments. If the first parameter had a rest operator, it would grab all the arguments, after which any subsequent parameters would be undefined.

For this reason, the Rest parameter can only be on the last parameter in the argument list.

Example in usage

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

foo(1, 2, 3, 4);
// 1
// [2, 3, 4]

If in some bizarre world, the Rest parameter could be on the first of many parameters, then we'd have something like this

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

foo(1, 2, 3, 4);
// [1, 2, 3, 4]
// undefined

And what use would that be...?

Rest parameter must be last formal parameter error:

function f(a, ...b, c) {
 // ...
}

right:

function f(a, b, ...c) {
 // ...
}

rest will be behave like default argument in other language(c++)

发布评论

评论列表(0)

  1. 暂无评论