Note that there are some explanatory texts on larger screens.

plurals
  1. POFlex How To Call A Function With A Variable Number Of Parameters?
    text
    copied!<p>Let's Say I Have This Class:</p> <pre><code>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 &lt; numbers.length; i++) { total += numbers [i]; } return total / numbers.length; } } } </code></pre> <p>How do I accomplish the "opposite" of this? Namely, how could I now CALL 'getAverage' with a dynamic number of paraemters?</p> <p>For instance, if I wanted to do something <strong>LIKE</strong>:</p> <pre><code>var r:int=Math.random()*6; var a:Array=new Array(); for (i:int=0;i&lt;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(???); </code></pre> <p>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...</p> <p><strong>NOTE:</strong> Answers consisting solely of "Why Do You Want To Do This?", will be downvoted.</p> <p>P.S. This <strong>IS NOT about calculating Averages!</strong> I <em>REALIZE</em> 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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload