AS3 … (rest) parameter

蹲街弑〆低调 提交于 2020-01-02 13:55:10

问题


I've tested the following code:

function aa(...aArgs):void
{
    trace("aa:", aArgs.length);
    bb(aArgs);
}
function bb(...bArgs):void
{
    trace("bb:", bArgs.length);
}
aa(); //calling aa without any arguments.

The output is:

aa: 0 //this is expected.
bb: 1 //this is not!

When I pass empty arguments (aArgs) to bb function; shouldn't it return 0 length? Seems like function bb is treating the passed aArgs as non-empty / non-null..

What am I missing here?

Any help is appreciated. regards..


回答1:


It looks like aArgs going to the bb() function would be an empty array, but an array none the less... I would say that output is to be expected. I'm not really sure though how I would format it differently though to get the desired output...

Update 1:

I wanted to clarify a little bit. What you have is basically the same thing as:

function aa(...aArgs):void
{
    myArray:Array = aArgs;
    bb(myArray);
}
function bb(...bArgs):void
{
    trace("bb:", bArgs.length);
}
aa(); //calling aa without any arguments.

If you saw this code, you would expect bb:1 yes?

Update 2:

This thread: filling in (...rest) parameters with an array? looks as though it would be relevant. It uses the apply() function to pass in an array as an parameter list. http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Function.html#apply()




回答2:


Don't know if this is still relevant but you could try this:

function aa(...aArgs):void {
    var myArray:Array = aArgs;
    bb.apply( this, myArray );
}
function bb(...bArgs):void {
    trace("bb:", bArgs.length);
}
aa(); //calling aa without any arguments.

Basically Function.apply is your friend here.




回答3:


This makes perfect sense, and working properly. ...rest always creates an Array, if there are no values passed in it creates an empty Array, as you see by tracing its length. So the reason why bb has one object in its ...rest array is that you are passing the empty array into bb as a value, which gets inserted into the first position of the Array generate by bb's ...rest, giving it a length of one.



来源:https://stackoverflow.com/questions/971475/as3-rest-parameter

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