Get a function's arity

旧街凉风 提交于 2019-11-26 07:36:28

问题


In Javascript, how can one determine the number of formal parameters defined for a function?

Note, this is not the arguments parameter when the function is called, but the number of named arguments the function was defined with.

function zero() {
    // Should return 0
}

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

function two(x, y) {
    // Should return 2
}

回答1:


> zero.length
0
> one.length
1
> two.length
2

Source

A function can determine its own arity (length) like this:

// 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
}



回答2:


A function's arity is stored in its .length property.

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



回答3:


As is covered in other answers, the length property tells you that. So zero.length will be 0, one.length will be 1, and two.length will be 2.

As of ES2015, we have two wrinkles:

  • Functions can have a "rest" parameter at the end of the parameter list which gathers up any arguments given at that position or afterward into a true array (unlike the arguments pseudo-array)
  • Function parameters can have default values

The "rest" parameter isn't counted when determining the arity of the function:

function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1

Similarly, a parameter with a default argument doesn't add to the arity, and in fact prevents any others following it from adding to it even if they don't have explicit defaults (they're assumed to have a silent default of undefined):

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

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



回答4:


A function arity is the number of parameters the function contains.It can be attained by calling the length property.

Example:

function add(num1,num2){}
console.log(add.length); // --> 2

function add(num1,num2,num3){}
console.log(add.length); // --> 3

Note: the number of parameters passed in a function call does not affect the function's arity.




回答5:


The arity property used to return the number of arguments expected by the function, however, it no longer exists and has been replaced by the Function.prototype.length property.



来源:https://stackoverflow.com/questions/4848149/get-a-functions-arity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!