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)
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)
如其他答案所述,该length属性告诉您。因此zero.length将为0,one.length将为1,two.length将为2。
截至ES2015,我们有两个皱纹:
arguments伪数组)确定该函数的arity时不计算“ rest”参数:
function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1Run 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); // 1Run Code Online (Sandbox Code Playgroud)