【问题标题】:Why arguments is given ...arguments in the arguments place like this?为什么在这样的参数位置给出参数......参数?
【发布时间】:2021-09-23 15:06:07
【问题描述】:

我的意思是:

function sum(...arguments) {
    if (arguments.length === 1) {
        const [firstArg] = arguments;
        if (firstArg instanceof Array) {
            return sum(...firstArg)
        }
    }
return arguments.reduce((a, b) => a + b);
}

这是什么……在争论面前做什么。还请帮助我知道为什么给出 const [firstArg] 以及它是如何工作的。请用简单的话向我解释 instanceof 。我的母语不是英语。非常感谢。

【问题讨论】:

标签: javascript html css reactjs


【解决方案1】:

那是rest syntax

其余参数语法允许函数接受不定数量的参数作为数组。

这个:

const [firstArg] = arguments;

destructuring assignment:

[it] 可以将数组中的值或对象中的属性解包到不同的变量中。

回复instanceOf:

The instanceof operator 测试构造函数的原型属性是否出现在对象原型链的任何位置。返回值是一个布尔值。

解压这段代码:

function sum(...arguments) {

  // arguments is an array thanks
  // to the rest syntax. If it has a length of
  // one...
  if (arguments.length === 1) {

    // Get the first element
    const [firstArg] = arguments;

    // If that element is an array
    if (firstArg instanceof Array) {

      // Call sum again with that element
      return sum(...firstArg)
    }
  }

  // Return the sum of the arguments
  return arguments.reduce((a, b) => a + b);
}

您的函数可以通过flattening 参数轻松简化,然后使用reduce 返回总和。通过这种方式,您甚至可以传入一组单个值,或 n 个多个数组作为函数的单个参数,或两者兼而有之。

function sum(...args) {
  return args.flat().reduce((acc, c) => acc + c, 0);
}

console.log(sum(1, 2, 3));
console.log(sum([1], 1, 2, 3));
console.log(sum([1, 2, 3]));
console.log(sum([1, 2], [1, 4, 3]));
console.log(sum([1, 2], [12, 20], [1, 4, 3]));

【讨论】:

  • 非常感谢@Andy。真的很有帮助。
【解决方案2】:

(...arguments) 是其余参数语法,它允许函数接受不定数量的参数作为数组,提供了一种在 JavaScript 中表示可变参数函数的方法。 更多信息,可以阅读here

const [firstArg] = arguments;

是一种名为解构赋值的东西 解构赋值语法是一种 JavaScript 表达式,它可以将数组中的值或对象中的属性解包到不同的变量中。

你可以阅读更多,here

最后,instanceof 运算符测试构造函数的原型属性是否出现在对象原型链的任何位置。返回值是一个布尔值

【讨论】:

    【解决方案3】:

    这是因为 ... 是一个 javascript 工具,它允许您将多个参数放入一个函数中,因此称为其余参数函数。

    【讨论】:

    • John,你真的可以让我了解一下这个功能如何在每一行上工作并做出决定。
    猜你喜欢
    • 2023-03-03
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 2021-10-17
    • 2019-09-21
    相关资源
    最近更新 更多