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

Referencing Array Elements

Once we've created an array, we'll inevitably want to retrieve or change the value of its elements. To do so, we use the array access operator, [].

Retrieving an Element's Value

To access an individual element, we provide a reference to the array followed by the element's index within square brackets, as follows:

theArray[elementNumber]

In the preceding code, theArray is a reference to the array (usually a variable with an array as a value), and elementNumber is an integer specifying the element's index. The first element is number 0, and the last element number is 1 less than the array's length. Specifying an element number greater than the last valid element number causes ActionScript to return undefined (because the specified index is outside the bounds of the array).

Let's try retrieving some element values. The following code creates an array using an array literal, and assigns it to the variable trees:

var trees:Array = ["birch", "maple", "oak", "cedar"];

The following code assigns the value of the first element of trees ("birch") to a variable, firstTree:

var firstTree:String = trees[0];

The following code assigns the third element's value ("oak") to the variable favoriteTree (remember that indexes start at 0, so index 2 is the third element!)

var favoriteTree:String = trees[2];

Now here's the fun part. Because we can specify the index of an element as any number-yielding expression, we can use variables or complex expressions just as easily as we use numbers ...

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