Loop Functions in Flash AS3
- The "for" loop carries out repetitive processing using a counter variable and a conditional test. The following sample code demonstrates a basic "for" loop:
var counter:int;
for(counter=0; counter<10; counter++) {
trace("Loop: " + counter);
}
This loop will output numerical values from zero to nine. When the code enters the loop, the counter variable is set to zero. Each time the loop iterates, the program checks the counter variable. If the variable is still less than ten, the content of the loop executes, then the counter variable is incremented, adding a value of one to it. The conditional test is then carried out again to check the value of the counter. When the value reaches 10, processing moves past the loop. - The "for in" loop allows programs to iterate through data structures such as arrays. The following code demonstrates:
var fruitCollection:Array = ["apple", "banana", "orange", "melon"];
for (var fruit:String in fruitCollection) {
trace("Fruit: " + fruit + " = " + fruitCollection[fruit]);
}
This code will output each element in the array in turn. There is no need to set up a conditional test checking the length of the array and the counter value, as AS3 will automatically stop when the array structure is exhausted. - The" for each in" loop also iterates through collections, but rather than using index values as references to positions within data structures such as arrays, it retrieves the element values themselves. The following sample code demonstrates:
var fruitCollection:Array = ["apple", "banana", "orange", "melon"];
for each (var fruitString in fruitCollection) {
trace("Fruit: " + fruitString);
}
There is no need to use the index value inside this loop, as the "for each" loop automatically accesses the element at each position in the structure. - The "while" loop allows you to carry out processing while some condition remains true. Like the "for" loop, the "while" loop uses a conditional test, as follows:
var counter:int = 0;
while (counter<10) {
trace("Loop: " + counter);
counter++;
}
This loop has the same effect as the example "for" loop, but a different implementation. The counter is initialized to zero before the loop begins, then the conditional test determines whether the loop content executes each time. The code inside the loop increments the counter as the last line of processing. - The "do while" loop is similar to the "while" loop, but allows programmers to ensure the loop content executes at least one time. The following sample code demonstrates:
var counter:int = 10;
do {
trace("Loop: " + counter);
counter++;
} while (counter<10);
If this action used a "while" loop, the content would never execute as the condition would return false even on the first iteration. This loop will execute once, then will only continue if the test returns true, which it will not in this case.
For Loop
For In Loop
For Each In Loop
While Loop
Do While Loop
Source...