AS3知道有多少参数的函数使用

问题描述:

有没有办法知道函数的一个实例多少参数可以在Flash?它也将是非常有用的知道,如果这些参数是可选的或不

Is there a way to know how many arguments an instance of Function can take in Flash? It would also be very useful to know if these arguments are optional or not.

例如:

public function foo() : void                               //would have 0 arguments
public function bar(arg1 : Boolean, arg2 : int) : void     //would have 2 arguments
public function jad(arg1 : Boolean, arg2 : int = 0) : void //would have 2 arguments with 1 being optional

感谢

是的有:使用Function.length属性。 我刚检查了文档:它似乎并没有被提及的还有,虽然

Yes there is: use the Function.length property. I just checked the docs: it doesn't seem to be mentioned there though.

trace(foo.length); //0
trace(bar.length); //2
trace(jad.length); //2

注意有没有括号()函数名后。你需要的功能对象的引用;加括号将执行功能。

Notice there are no braces () after the function name. You need a reference of the Function object; adding the braces would execute the function.

我不知道的方式,以确定其中一个参数是可选的,但。

I do not know of a way to ascertain that one of the arguments is optional though.

修改

什么...rest参数?

function foo(...rest) {}
function bar(parameter0, parameter1, ...rest) {}

trace(foo.length); //0
trace(bar.length); //2

这是有道理的,因为没有办法知道有多少参数将被通过了。 请注意,在函数体内,你就可以知道到底有多少参数被传递,就像这样:

This makes sense since there is no way of knowing how many arguments will be passed. Note that within the function body you can know exactly how many arguments were passed, like so:

function foo(...rest) {
    trace(rest.length);
}

感谢@felipemaia指出了这一点。

Thanks to @felipemaia for pointing that out.