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.
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:
arrayName[elementNumber]
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 intreesvar trees = ["birch", "maple", "oak", "cedar"]; // Display the first element oftreesin the Output window trace(trees[0]); // Displays: "birch" // Assign the third element's value to the variablefavoriteTree// (remember indexes start at 0, so index 2 is the third element!!) var favoriteTree = trees[2]; //favoriteTreebecomes "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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access