AS3: Passing an array into a function using the …rest parameter

I’m building an accordion menu for a current Actionscript 3.0 Flash project and have decided to use the … rest parameter in my accordion-building function to allow for a variable list length. The catch I’ve found is that while …rest is an array type, simply passing an array into the argument will treat it as a single String. An example:

function myFunction(... rest):void {
   trace(rest.length + ": " + rest);
   trace(rest[2]);
}
var myArray:Array = new Array("this","is","my", "list", "of", "arguments");
myFunction(myArray);
/*
OUTPUTS:
1: this,is,my,list,of,arguments
undefined
*/

You’ll notice that the length of the argument array is 1 and that querying a specific key beyond the argument length yields undefined.

If you want to instead submit the array as a series of arguments (and take advantage of …rest) do this instead:

function myFunction(... rest):void {
   trace(rest.length + ": " + rest);
   trace(rest[2]);
}
var myArray:Array = new Array("this","is","my", "list", "of", "arguments");
myFunction.apply(this, myArray);
/*
OUTPUTS:
6: this,is,my,list,of,arguments
my
*/

Leave a Reply


Bad Behavior has blocked 349 access attempts in the last 7 days.