获取函数的参数 [英] Get a function's arity

查看:144
本文介绍了获取函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,如何确定为函数定义的形式参数的数量?注意,这不是参数

code>参数,但函数被定义的命名参数的数量。

 函数零(){
//应该返回0
}

函数one(x){
//应该返回1
}

函数two(x,y){
//应该返回2
}


解决方案

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

来源



函数可以确定自己的长度像这样:

  //对于IE和ES5严格模式(命名函数)
函数foo(x,y ,z){
return foo.length; //返回3
}

//否则
函数bar(x,y){
返回arguments.callee.length; //将返回2
}


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
}

解决方案

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

这篇关于获取函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆