Rest Parameter: Pass any number of values, its easy as ...

28. January 2009 21:59

I was doing a bit of reading tonight and happened upon a piece of info that was totally new to me.  After being in the flash/flex arena for a few years now, I've become quite comfortable with functions and passing arguments, but, as they say, it's never too late to learn something new.  Tonight, while reading the Actionscript 3.0 Bible, I happened upon a way to pass any number of arguments to a function without a bunch of hassle.  In Actionscript 3.0, there is a new feature called the "rest parameter."  Instead of having to populate and then pass an array to a function, using the rest parameter allows you to call the function and pass any number of arguments.  Let me illustrate this with some code:



<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
    <mx:Script>
        <![CDATA[
            [Bindable]
            private var sum:Number = 0;
           
            private function initApp():void
            {
                getValue(1,2,3);
            }
           
            public function getValue(... myValues):void
            {
                for each(var num:Number in myValues)
                {
                    sum += num;
                }
            }
           
        ]]>
    </mx:Script>
    <mx:Label text="{sum}"/>
</mx:Application>

 You will notice the parameter list for the getValue function contains an ellipsis (...) and the word "myValues."  The ellipsis is the rest parameter which instructs the program to allow any number of values to be passed.  When the values are passed, the are placed into an array called myValues.  You can then use the array like any other array.

Sweet.


Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments


Log in