AS3.0 TutBits #02: Unknown number of parameters
The second TutBit is dealing with creating a method/function which takes an arbitrary number of arguments. This makes the creation of very flexible function calls possible. Have a look at the following example:
private function showFavouriteMovies( name:String, ...movies:Array ):void { var retString:String = name + "'s favourite movies are: "; for (var i:uint = 0; i < movies.length; i++) { retString += movies[i]; if ( i < (movies.length-1) ) { retString += ", "; } } trace(retString + "."); }
The created method called showFavouriteMovies() takes two arguments. The first parameter called “name” is a normal parameter of type String. The second parameter “…movies” defines an array to hold any arguments passed to the method. The name after the “…”-construct defines the name of the array (here it is “movies”).
So, calling the function for example with the following paramters:
showFavouriteMovies("Joshua", "Wargames", "13th Floor", "The beach");
will result in:
Joshua's favourite movies are: Wargames, 13th Floor, The beach.
You see that the first named paramter called “name” can be used normally. The list of movies are stored in an indexed array where the first element (i.e. index 0) is the left-most value of the method call (in our example it is “Wargames”) proceeding to the right.
Always keep in mind, that the “…”-construct must be the last parameter in your method’s signature.
