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



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

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

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

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

它基本上是arguments对象的替换。而不是写作

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

你可以写

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

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

<小时 />

controller.update(...args),请参阅"foo(...arg("(函数调用中的三个点(?.

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

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

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

展开运算符 ( ... ( 允许我们接受可变数量的参数并将它们存储在数组中。然后,我们再次使用 spread 运算符将它们传递给 update 函数:

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

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

"...args"(三个点(是Javascript扩展运算符。

function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6

如果你知道一些Python语法,它和*args完全一样。由于*args(Python(是元组对象,而Javascript没有像Python那样的元组,因此..args是一个数组对象。

表示传递所有值(如果具有未知#项,则很有用(

示例代码

console.log(sum(1, 2, 3, 4));  // expected output: 10
function sum(...allItems) { 
  let total = 0;
  for (const item of allItems) {
     total += item;
   }
   return total;
}

它被称为"rest 参数",您可以使用 rest 参数将未指定数量的参数作为数组传递,并且一个函数只能有一个 rest 参数,并且它必须是函数的最后一个参数

    function sum(...args){
    let output = 0;
     for(const num of args){
     output += num;
     }
        return output;
     }
     console.log(sum(2,4,8));

在这里,它将传递 sum 的参数作为数组,并对输出求和并返回

最新更新