AS3 … (rest) parameter

2019-05-26 04:35发布

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

3条回答
聊天终结者
2楼-- · 2019-05-26 04:54

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楼-- · 2019-05-26 04:55

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.

查看更多
混吃等死
4楼-- · 2019-05-26 04:59

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()

查看更多
登录 后发表回答