Flex Tip of the Day: varargs in AS3

Before I leave for my trip, I thought I’d post another tip in my series of tips for Flex beginners

varargs in AS3

Did you know that just like the varargs functionality in Java you could define an ActionScript function so that it takes a variable number of arguments?

You can do this using two approaches: arguments object or … (rest) parameter I am giving a brief example of the … (rest) parameter approach here, you can read in detail about both approaches in this article on Livedocs

// Here's a bare bone example:

            private function average(... args):Number{
               var sum:Number = 0;
               for(var i:int = 0; i<args.length;i++){
                       sum += args[i];
               }
               return sum/args.length;
            }

// Now all the below calls would work

               var a:Number = average(100,200);
               a = average(100,200,300);
               a = average(100,200,300,400);
               a = average(100,200,300,400,500);


About this entry