函数定义中"... args"(三个点)的含义是什么?

Ces*_*uez 18 javascript express ecmascript-6

在Javascript中阅读此语法对我来说真的很混乱:

router.route('/:id')
.put((...args) => controller.update(...args))
.get((...args) => controller.findById(...args));
Run Code Online (Sandbox Code Playgroud)

什么... args意味着什么?

Fel*_*ing 27

关于o (...args) =>,...args休息参数.它始终必须是参数列表中的最后一个条目,并且将为其分配一个数组,该数组包含尚未分配给先前参数的所有参数.

它基本上是arguments对象的替代品.而不是写作

function max() {
  var values = Array.prototype.slice.call(arguments, 0);
  // ...
}
max(1,2,3);
Run Code Online (Sandbox Code Playgroud)

你可以写

function max(...value) {
  // ...
}
max(1,2,3);
Run Code Online (Sandbox Code Playgroud)

此外,由于箭头函数没有arguments对象,因此这是创建可变参数(箭头)函数的唯一方法.


as controller.update(...args),请参阅"foo(... arg)"的含义是什么(函数调用中的三个点)?.


bej*_*ado 12

基本上,正在做的是这样的:

.put((a, b, c) => controller.update(a, b, c))
Run Code Online (Sandbox Code Playgroud)

当然,如果我们想要4个参数,或5个或6个怎么办?我们不想为所有可能数量的参数编写新版本的函数.

价差运营商(...)使我们能够接受可变数量的参数,并将其存储在数组中.然后我们再次使用spread运算符将它们传递给update函数:

.put((...args) => controller.update(...args))
Run Code Online (Sandbox Code Playgroud)

这对update函数是透明的,函数接收它们作为普通参数.

  • [`......`不是运营商](http://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/ 37152508#37152508)这与传播无关. (3认同)