home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book HomeActionScript: The Definitive GuideSearch this book

11.4. 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 can use square brackets (i.e., the array access operator), [], which was introduced in Chapter 5, "Operators".

11.4.1. Retrieving an Element's Value

In order to obtain an element's value, we simply refer to the element by supplying its index within square brackets, like this:


where arrayName must be an array and elementNumber can be any expression that yields a numeric value. The first element is number and the last element number is one less than the array's length. Specifying an element number greater than the last valid element number causes the interpreter to return undefined. For example:

// Create an array using an array literal, and store it in trees
var trees = ["birch", "maple", "oak", "cedar"];

// Display the first element of trees in the Output window
trace(trees[0]);  // Displays: "birch"

// Assign the third element's value to the variable favoriteTree
// (remember indexes start at 0, so index 2 is the third element!!)
var favoriteTree = trees[2];  // favoriteTree becomes "oak"

Now the fun part. Since we can provide the index of an element as any number-yielding expression, we may use variables just as easily as we use numbers to specify an element index. For example:

var i = 3;
var lastTree = trees[i];  // Set lastTree to "cedar"

We can even use function-call expressions that have numeric return values as our array indexes:

// Set randomTree to a randomly picked element of trees
// by calculating a random number between 0 and 3
var randomTree = trees[Math.floor(Math.random( ) * 4)];

Hot dog, that's powerful! You might use a similar approach to pick a random question from an array of trivia questions or to pick a random card from an array that represents a deck of cards.

Note that accessing an array is very similar to accessing a variable value. Array elements can be used as part of a complex expression, as follows:

var myNums = [12, 4, 155, 90];
var myTotal = myNums[0] + myNums[1] + myNums[2] + myNums[3];   // Sum the array

The approach used in the previous example to total the values of an array's elements isn't exactly the paragon of optimized code. Later, we'll see a much faster and more convenient way to access an array's elements sequentially.

Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.