3

my question is the Flex transposition of this question :

Can I pass an array as arguments to a method with variable arguments in Java?

That is, I have an Array in some Actionscript code and i need to pass every object indexed in the array into a method method(...arguments).

Some code to make it clear:

private function mainMethod():void{
    var myArray:Array = new Array("1", "2", "3");
    // Call calledMethod and give it "1", "2" and "3" as arguments
}

private function calledMethod(...arguments):void{
    for each (argument:Object in arguments)
        trace(argument);
}

Is there some way to do what the comment suggests?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! I had this exact problem, myself, a few days ago.
1

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.

1 Comment

Is there no way to circumvent this ?
0

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

1 Comment

Sorry but it doesn't help. My question specifically addresses the problem of passing to such a method the objects contained in an array. This means that you cannot explicit these objects in the method call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.