Flex How to call a function with a variable number of parameters?

Say I have this class:

package{
  import flash.display.Sprite;
  public class Main extends Sprite{
    public function Main(){
        trace(getAverage(1,2,3));
        trace(getAverage(1,2,3,4));
        trace(getAverage(1,2,3,4,5));
    }
    public function getAverage (...numbers) {
      var total = 0;
      for (var i = 0; i < numbers.length; i++) {
        total += numbers [i];
      }
      return total / numbers.length;
    }
  }
}

How do I accomplish the "opposite" of this? Namely, how could I now call "getAverage" with a dynamic number of repeaters?

For example, if I wanted to do something LIKE :

var r:int=Math.random()*6;
var a:Array=new Array();
for (i:int=0;i<r;i++) {
  a[i]=Math.random()*22;
}
// Now I have 'r' Number Of Parameters Stored In 'a'
//   How Do I Call getAverage, with all the values in 'a'??
//   getAverage(a) isn't right, is it?
//   I'm looking for something similar to getAverage(a[0],a[1],a[...]);

var av:Number=getAverage(???);

What I want to know is that if I have a function that takes a variable number of arguments, that's great, but how can I call IT with a variable number of arguments when that number is unknown at runtime? Perhaps this is impossible ... I'm just not sure, since "callLater" seems to be able to take an array and create a dynamic number of parameters from it ...

. , " ?", .

P.S. . ! ( getAverage, ). - , . ?

+5
5

, ?

var av:Number = getAverage.apply(null, a);
+9
+3

, arguments , (... args) . , ...

0

. .

0

Flash has some pretty powerful introspection capabilities. Thus, instead of passing multiple objects, you simply pass one dynamic object with any number of attributes you need:

var ob:Object={arg1:"value1", arg2:8}; 
var arg:String="arg4";
ob["arg3"]=8;
ob[arg]=18;
trace (ob.hasOwnProperty("arg1"));
trace (ob.arg3);
trace (ob.arg4);

This should cover almost any use case you might need. The downside is that it allows some pretty smart and hard to track bugs. :-)

0
source

All Articles