Passing arguments from an array to an ActionScript method with an argument ... (rest)

my question is transposing Flex to this question:

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

That is, I have Array in some ActionScript code, and I need to pass each object indexed into an array to the 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 a way to do what the comment suggests?

+3
source share
3 answers

This is 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 information check out http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply ()

+10
source

It's hard for the compiler to guess what you want, want to pass a single argument of type Array, or you want to pass the elements of this array. The compiler is suitable for speculation.

+1
source

... args is the one object that the method expects. You can pass multiple elements or (in this case) a single array with 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 this helps, Rob

0
source

All Articles