JavaScript的高阶函数如何解释回调函数参数?

How do JavaScript's higher order functions interpret callback function parameters?

我一直在使用高阶函数并取得了一些成功,但我对回调参数的工作方式有点困惑。 Reduce,例如,有几个参数(累加器、currentValue 等)。命名似乎并不重要。如果需要,我可以用 'acc' 替换 accumulator 的使用,或者用完全不同的词替换它。这让我相信 reduce 会按照给定的顺序解释参数。对吗?

如果是这样,我如何指示我只需要在列表后面使用一个参数?假设我只打算使用 currentIndex。我是否需要为 currentIndex 之前的两个(累加器和 currentValue)输入参数值,即使我没有使用它们?

That leads me to believe reduce interprets parameters by the order they are given. Is that correct?

是的,参数的顺序很重要,命名并不重要,除了名称可能有助于您更好地识别参数的目的。

If so, how do I indicate that I only need to use a parameter later in the list? Let's say I only intend on using currentIndex. Would I need to enter parameter values for the two before currentIndex (accumulator and currentValue) even though I'm not using them?

是的,您需要输入所有参数名称 "reach" 您想要的参数。

您不一定非要使用这些参数。例如:

function hello () {
  return "hi"
}

console.log([1, 2, 3, 4].reduce(hello))   // prints "hi"

愚蠢的例子,但我想表明我实际上并没有使用任何 reduce 函数参数,只是返回我想要的任何东西。这仍然有效,但显然违背了使用 reduce 函数的目的。

感谢@andrew-li,如果您根本不打算使用给定的参数,请为变量命名,以便轻松确定它是未使用的变量:

function hello (dummy1, dummy2, cidx) {
  return cidx
}

console.log([1, 2, 3, 4].reduce(hello))   // 4