获取函数的数量 [英] Get a function's arity
本文介绍了获取函数的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Javascript 中,如何确定为函数定义的形式参数的数量?
In Javascript, how can one determine the number of formal parameters defined for a function?
注意,这不是调用函数时的 arguments
参数,而是定义函数时使用的命名参数的数量.
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
}
推荐答案
> zero.length
0
> one.length
1
> two.length
2
一个函数可以像这样确定它自己的数量(长度):
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
}
这篇关于获取函数的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文