Javascript 函数定义中的“...args”(三个点)是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42184674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:58:47  来源:igfitidea点击:

What is the meaning of "...args" (three dots) in a function definition?

javascriptexpressecmascript-6

提问by Cesar Jr Rodriguez

It was really confusing for me to read this syntax in Javascript:

在 Javascript 中阅读这个语法对我来说真的很困惑:

router.route('/:id')
.put((...args) => controller.update(...args))
.get((...args) => controller.findById(...args));

What does ...argsmean?

什么参数... args是什么意思?

回答by Felix Kling

With respect o (...args) =>, ...argsis a rest parameter. It always has to be the last entry in the parameter list and it will be assigned an array that contains all arguments that haven't been assigned to previous parameters.

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

It's basically the replacement for the argumentsobject. Instead of writing

它基本上是argumentsobject的替代品。而不是写作

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

you can write

你可以写

function max(...value) {
  // ...
}
max(1,2,3);

Also, since arrow functions don't have an argumentsobject, this is the only way to create variadic (arrow) functions.

此外,由于箭头函数没有argumentsobject,这是创建可变参数(箭头)函数的唯一方法。



As controller.update(...args), see What is the meaning of "foo(...arg)" (three dots in a function call)?.

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

回答by bejado

Essentially, what's being done is this:

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

.put((a, b, c) => controller.update(a, b, c))

Of course, what if we want 4 parameters, or 5, or 6? We don't want to write a new version of the function for all possible quantities of parameters.

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

The spread operator(...) allows us to accept a variable number of arguments and store them in an array. We then use the spread operator again to pass them to the updatefunction:

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

.put((...args) => controller.update(...args))

This is transparent to the updatefunction, who receives them as normal arguments.

这对update函数来说是透明的,函数将它们作为普通参数接收。

回答by Ramesh

The meaning of “…args” (three dots) is Javascript spread operator.

“...args”(三个点)的意思是Javascript 扩展运算符

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6