`Function.prototype.length` 到底是什么意思?

What exactly `Function.prototype.length` means?

有一个Function.prototype.arity property purposed for getting number of arguments function expects. Now it is obsolete (since JS 1.4), and the same goal has Function.prototype.length

但最近我在文档中找到一篇关于 Array.prototype.reduce 方法的文章。它清楚地表明该方法 属性 length 等于 1:

The length property of the reduce method is 1.

这篇文章有一个 header 个参数,其中有两个:

Array.prototype.reduce ( callbackfn [ , initialValue ] )

callbackfninitialValue(可选)。

所以我不清楚 length 属性.
的目的到底是什么 如果它是用来为开发者提供有用的信息,那么它实际上并没有。
如果只是技术上的automatically-generated 属性 只是表示函数定义中的参数个数,那为什么不保持它的一致性呢?

Array.prototype.reducelength是1因为第二个参数是可选的*

So it is not clear to me, what exactly the purpose of length property.

告诉开发者在第一个有默认值的参数(如果有的话)或其余参数(如果有的话)之前有多少声明参数,以先到者为准在参数列表中。或者如 the spec puts it:

The value of the length property is an integer that indicates the typical number of arguments expected by the function.

具体算法在the spec's Static Semantics: ExpectedArgumentCount section.

If it is used to give useful information to developer, then it actually does not.

好吧,这是一个见仁见智的问题。 :-)

当你有像 JavaScript 这样的语言时,函数只能表达期望,但可以用更少或更多的参数调用,特别是当你添加默认参数值和剩余参数的概念时,它不是令人惊讶的是,功能的多样性是一个软概念。

一些有趣的例子:

function ex1(a) { }             // length is 1, of course
function ex2(a, b = 42) { }     // length is 1, `b` has a default
function ex3(a, b = 42, c) { }  // length is 1, `b` has a default and
                                // `c` is after `b`
function ex4(a, ...rest) { }    // length is 1 yet again, rest parameter doesn't count

* 在 ES5 中,它在 JavaScript 中的声明将是:

function reduce(callback) {
    // ...
}

...然后它会使用 arguments.length 来确定您是否认为 initialValue.

在 ES2015+(又名 "ES6"+)中,它要么仍然是那样,要么像这样:

function reduce(callback, ...args) {
    // ...
}

...并使用args.length查看是否有初始值。

或者可能是这样的:

const omitted = {};
function reduce(callback, initialValue = omitted) {
    // ...
}

...然后使用 initialValue === omitted 了解您是否提供了初始值。 (initialValue 的默认值不能是 undefinednull 或类似的,因为函数必须根据是否提供参数 [而不是它的值是什么] 进行分支。但是我们可以使用对象身份来做到这一点。)