views:

709

answers:

4

Does ActionScript 3.0 offer any means to accept an arbitrary number of parameters? I usually use .NET, but I'm being forced to use AS3 for a project and something along the lines of function blah(params double[] x) would be awesome for a helper library.

Thanks;

+8  A: 

Check out the rest parameter: http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/statements.html#..._(rest)_parameter

package {
  import flash.display.MovieClip;

  public class RestParamExample extends MovieClip {
    public function RestParamExample() {
        traceParams(100, 130, "two"); // 100,130,two
        trace(average(4, 7, 13));     // 8
    }
  }
}


function traceParams(... rest) {
 trace(rest);
}

function average(... args) : Number{
  var sum:Number = 0;
  for (var i:uint = 0; i < args.length; i++) {
    sum += args[i];
  }
  return (sum / args.length);
}
Christophe Herreman
Is it possible to specify the type for args? ie, ... args : int?
hb
Nevermind - you can't
hb
+2  A: 

Try an ellipse (like C) ...

function trace_all (... args): void {
    for each (a in args) {
       trace (a);
    }
}
eduffy
A: 

If you want to pass an undetermined number of ordered values just pass an array

function foobar(values:Array):void
{
    ...
}


foobat([1.0, 3.4, 4.5]);
foobat([34.6, 52.3, 434.5, 3344.5, 3562.435, 1, 1, 2, 5]);

If you want to pass named parameters where only some of them are passed then use an object

   function woof(params:object):string
   {
       if (params.hasProperty('name')) {
           return name + "xxx";
       }
       ...
   }

   woof({name:'Joe Blow', count: 123, title: 'Mr. Wonderful'});
James Keesey
+2  A: 

In addition to the "rest" parameter, there is an "arguments" object.

function foo() {
    for (var i:Number = 0; i < arguments.length; i++) {
        trace(arguments[i]);
    }
}
Parappa