Pass arguments from an array to an Actionscript method with …(rest) argument

核能气质少年 提交于 2019-12-01 09:14:27

It's possible by going through the Function object itself. Calling apply() on it will work:

private function mainMethod():void
{
    var myArray:Array = new Array("1", "2", "3");

    // call calledMethod() and pass each object in myArray individually
    // and not as an array
    calledMethod.apply( this, myArray );
}

private function calledMethod( ... args ):void
{
    trace( args.length ); // traces 3
}

For more info, check out http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()

It is kind of hard for the compiler to guess what you want, do you want to pass one argument of type Array or do you want to pass the elements of that array. The compiler goes for assumption one.

The ...args is one Object the method awaits for. You can pass multiple elements or (in this case) one array with the parameters.

Example:

function mainMethod():void
{
    //Passing parameters as one object
    calledMethod([1, 2, 3]);

    //Passing parameters separately
    calledMethod(1, 2, 3);
}

function calledMethod(...args):void
{
    for each (var argument in args)
    {
        trace(argument);
    }
}

mainMethod();

Hope it helps, Rob

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