Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Syntax and Language Fundamentals > About statements > Repeating actions using loops > Using while loops | |||
Use the while statement to repeat an action while a condition exists, similar to an if statement that repeats as long as the condition is true.
A while loop evaluates an expression and executes the code in the body of the loop if the expression is true. If the condition evaluates to true, a statement or series of statements runs before looping back to evaluate the condition again. When the condition evaluates to false, the statement or series of statements is skipped and the loop ends. Using while loops can be very useful when you aren't sure of how many times you'll need to loop over a block of code.
For example, the following code traces numbers to the Output panel:
var i:Number = 0;
while (i < 5) {
trace(i);
i++;
}
You see the following numbers traced to the Output panel:
0 1 2 3 4
One disadvantage of using a while loop instead of a for loop is that infinite loops are easier to write with while loops. The for loop example code does not compile if you omit the expression that increments the counter variable, but the while loop example does compile if you omit that step. Without the expression that increments i, the loop becomes an infinite loop.
To create and use a while loop in a FLA file, follow this example.
To create a while loop:
var users_ds:mx.data.components.DataSet;
//
users_ds.addItem({name:"Irving", age:34});
users_ds.addItem({name:"Christopher", age:48});
users_ds.addItem({name:"Walter", age:23});
//
users_ds.first();
while (users_ds.hasNext()) {
trace("name:" + users_ds.currentItem["name"] + ", age:" + users_ds.currentItem["age"]);
users_ds.next();
}
The following information is displayed in the Output panel:
name:Irving, age:34 name:Christopher, age:48 name:Walter, age:23
For more information, see the while statement in the ActionScript 2.0 Language Reference.
|
|
|
|