O'Reilly logo

Essential ActionScript 3.0 by Colin Moock

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Handling an Unknown Number of Parameters

In Chapter 1, we learned that it is illegal to call a method without supplying arguments for all required parameters. It is also illegal to call a method with more than the required number of arguments.

To define a method that accepts an arbitrary number of arguments, we use the ...(rest) parameter. The ...(rest) parameter defines an array to hold any arguments passed to a given method. It can be used on its own or in combination with named parameters. When used on its own, the ...(rest) parameter has the following general form:

function methodName (...argumentsArray) {
}

In the preceding code, methodName is the name of a method (or function), and argumentsArray is the name of a parameter that will be assigned an automatically created array of all arguments received by the method. The first argument (the leftmost argument in the call expression) is stored at index 0 and is referred to as argumentsArray[0]. Subsequent arguments are stored in order, proceeding to the right—so, the second argument is argumentsArray[1], the third is argumentsArray[2], and so on.

The ...(rest) parameter allows us to create very flexible functions that operate on an arbitrary number of values. For example, the following code shows a method that finds the average value of any numbers it received as arguments:

public function getAverage (...numbers) {
  var total = 0;

  for (var i = 0; i < numbers.length; i++) {
    total += numbers [i];
  }

  return total / numbers.length;
}

Note ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required