6.2. Looping Through an Array

Problem

You want to access or process all of the elements of an array in sequential order.

Solution

Use a for loop that increments an index variable from 0 to Array. length - 1. Use the index to access each element in turn.

Discussion

To access the values stored in the elements of an array, loop through the array’s elements using a for loop. Because the first index of an array is 0, the index variable in the for statement should start at 0. The last index of an array is always 1 less than the length property of that array. Within the for statement, you can use the loop index variable within square brackets to access array elements. For example:

myArray = ["a", "b", "c"];
for (var i = 0; i < myArray.length; i++) {
  // Display the elements in the Output window.
  trace("Element " + i + ": " + myArray[i]);
}

The looping index variable (i in the example code) should range from 0 to one less than the value of the length property. Remember that the last index of an array is always one less than its length.

Alternatively, you can also use a for statement that loops backward from Array. length - 1 to 0, decrementing by one each time. Looping backward is useful when you want to find the last matching element rather than the first (see Recipe 6.3). For example:

myArray = ["a", "b", "c"];
for (var i = myArray.length - 1; i >= 0; i--){
  // Display the elements in the Output window in reverse order.
  trace("Element " + i + ": " + myArray[i]);
}

There are many examples in which ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.