Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex How To Call A Function With A Variable Number Of Parameters?

Let's 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 paraemters?

For instance, 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 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 isn't known at runtime? Possibly it's impossible... I'm just not sure, since 'callLater' seems to be able to take an array and generate a dynamic number of parameters from it somehow...

NOTE: Answers consisting solely of "Why Do You Want To Do This?", will be downvoted.

P.S. This IS NOT about calculating Averages! I REALIZE There Are Way Simpler Ways Of Doing All Of This! (I could just write getAverage to accept a single array as its only parameter) The Above is just an EXAMPLE to Illustrate my Question. HOW TO PASS A DYNAMIC NUMBER OF PARAMETERS TO A FUNCTION?

like image 229
Joshua Avatar asked Oct 04 '10 04:10

Joshua


1 Answers

Is this what you're looking for?

var av:Number = getAverage.apply(null, a);
like image 59
dchang Avatar answered Oct 21 '22 07:10

dchang