Recipe 5.2. Looping
Through an Array
Problem
You want to access each element of an array in
sequential order.
Solution
Use a for loop that increments an index
variable from 0 until it reaches Array.
length. 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, use the loop index variable within square brackets to
access array elements. For example:
var letters:Array = ["a", "b", "c"];
for (var i:int = 0; i < letters.length; i++) {
// Display the elements in the Output panel.
trace("Element " + i + ": " + letters[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 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
5.3), for example:
var letters:Array = ["a", "b", "c"];
for (var i:int = letters.length - 1; i >= 0; i--){
// Display the elements in reverse order.
trace("Element " + i + ": " + letters[i]);
}
There are many instances when you might want to
loop through all the elements of an array. For example, by looping
through an array containing references to sprites, you can perform
a particular action on each of the sprites:
for (var i:int = 0; i < sprites.length; i++){
// Move each sprite one pixel to the right.
sprites[i].x++;
}
You can store the array's length in a
variable rather than computing it during each loop iteration. For
example:
var length:int = sprites.length;
for (var i:int = 0; i < length; i++){
// Move each sprite one pixel to the right.
sprites[i].x++;
}
The effect is that there is a very marginal
performance improvement because Flash doesn't have to calculate the
length during each iteration. However, it assumes that you are not
adding or removing elements during the loop. Adding or removing
elements changes the length property. In such a case, it is better
to calculate the length of the array with each iteration.
See Also
Recipe
12.8 for ways to loop through characters in a string. Recipe
5.16 for details on enumerating elements of an associative
array. See also Recipe
5.3.
|