Methods with unknown number of parameters

Recently I am studying “Essential Actionscript 3.0” by Colin Mook. I am in the first chapter itself and informations are already there to digest. I simply love the Mook’s books. Previously it was for AS2 and that was too good, now this is an excellent addition. This writing simply brings the books pages to here with my own edits :) .
Ok, straight to the point, how to write a method,  inside a class, which can handle “multiple” or better word as per Mook is “unknown” number of parametrs ?!! The answer is “…(rest)” parameter. This parameter defines an Array to hold any number of arguments passed to a given method. It can be used on its own or in combination with named parameters.
Using the parameter alone :
function myFun(…what){
for(var i:int=0;i<what.length;i++){

Now try to call the function with some new number of parameters as
The result will be obviuos.Lets try to use the “…(rest)” parameter with a named parameter.
function samAdd(a:int,…more){
var addValue:int=a;
for(var j:int;j<more.length;j++){

I have simply added “sam” before the function name, instead of my name “saumya” :) . Ok, now if you look at the result it will give you “14”.Lets the call the function with the desired number of parameter, which is 1.I mean you must pass one parameter to successfully call this function.So the next call will be
This will result in “20”, but what happens if we call it without any parameter as
The compiler throws an error saying “Incorrect number of arguments.Expected 1.”

When used with other parameters, the “…(rest)” parameter must be the last parameter in the parameter list.That means, we can not write
function samAdd(…more,a:int){
//code to be executed

For me, its just WOW.

Cheers to Mook. I will put things like this as i proceed through the book.


3 thoughts on “Methods with unknown number of parameters

  1. i’m going thru Moock’s book also and found EAS3 to be a very substandard follow up to EAS2. The code is buggy and the book is very poorly structured – too much forward looking instructions. Also, EAS2 was a good introduction into OOP but EAS3 is an odd follow up with its many how -to sections. Now i’m waiting for the definitive EAS3, possibly AS3 bible? anyhow, good luck

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s