得到一个功能的arity

Jas*_*ith 53 javascript functional-programming arity

在Javascript中,如何确定为函数定义的形式参数的数量?

注意,这不是arguments调用函数时的参数,而是函数定义的命名参数的数量.

function zero() {
    // Should return 0
}

function one(x) {
    // Should return 1
}

function two(x, y) {
    // Should return 2
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*Lee 62

> zero.length
0
> one.length
1
> two.length
2
Run Code Online (Sandbox Code Playgroud)

资源

函数可以像这样确定自己的arity(length):

// For IE, and ES5 strict mode (named function)
function foo(x, y, z) {
    return foo.length; // Will return 3
}

// Otherwise
function bar(x, y) {
    return arguments.callee.length; // Will return 2
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这与`arguments.length`不同,后者是实际接收的参数数量. (7认同)
  • @jhs:还要注意`arguments.callee`在ECMAScript 5严格模式下抛出一个错误,这意味着它已经被有效地从语言中删除了. (4认同)

Jas*_*ith 11

函数的arity存储在其.length属性中.

function zero() {
    return arguments.callee.length;
}

function one(x) {
    return arguments.callee.length;
}

function two(x, y) {
    return arguments.callee.length;
}

> console.log("zero="+zero() + " one="+one() + " two="+two())
zero=0 one=1 two=2
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 6

如其他答案所述,该length属性告诉您。因此zero.length将为0,one.length将为1,two.length将为2。

截至ES2015,我们有两个皱纹:

  • 函数可以在参数列表的末尾具有一个“ rest”参数,该参数将收集在该位置或此后给出的所有参数放入真实数组中(不同于arguments伪数组)
  • 函数参数可以具有默认值

确定该函数的arity时不计算“ rest”参数:

function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1
Run Code Online (Sandbox Code Playgroud)

类似地,带有默认参数的参数不会添加到arity中,并且实际上阻止了跟随它的其他任何人都添加到该参数中,即使它们没有显式的默认值(假定它们具有的默认默认值undefined):

function oneAgain(a, b = 42) { }
console.log(oneAgain.length);    // 1

function oneYetAgain(a, b = 42, c) { }
console.log(oneYetAgain.length); // 1
Run Code Online (Sandbox Code Playgroud)

  • @JasonSmith:没有任何东西不依赖于反编译(例如“Function#toString”)。 (2认同)