Flash CS3 Documentation |
|||
| Learning ActionScript 2.0 in Adobe Flash > Syntax and Language Fundamentals > About statements > Repeating actions using loops > Using for loops | |||
The for loop lets you iterate over a variable for a specific range of values. A for loop is useful when you know exactly how many times you need to repeat a series of ActionScript statements. This can be useful if you want to duplicate a movie clip on the Stage a certain number of times or to loop over an array and perform a task on each item in that array. A for loop repeats an action using a built-in counter. In a for statement, the counter and the statement that increments the counter are all part of the for statement. You write the for statement using the following basic format:
for (init; condition; update) {
// statements;
}
You must supply three expressions to a for statement: a variable that is set to an initial value, a conditional statement that determines when the looping ends, and an expression that changes the value of the variable with each loop. For example, the following code loops five times. The value of the variable i starts at 0 and ends at 4, and the output are the numbers 0 through 4, each on its own line.
var i:Number;
for (i = 0; i < 5; i++) {
trace(i);
}
In the next example, the first expression (i = 0) is the initial expression that evaluates before the first iteration. The second expression (i < 5) is the condition that you check each time before the loop runs. The third expression (i++) is called the post expression and is evaluated each time after the loop runs.
var i:Number;
for (i = 0; i < 5; i++) {
this.attachMovie("libraryLinkageClassName", "clip" + i + "_mc", i, {_x:(i * 100)});
}
Notice how five movie clips duplicate across the top of the Stage. This ActionScript duplicates the movie clip symbol in the library and repositions the clips on the Stage at x coordinates of 0, 100, 200, 300 and 400 pixels. The loop executes five times, with the variable i assigned a value of 0 through 4. On the last iteration of the loop, the value of i increments to 4 and the second expression (i < 5) is no longer true, which causes the loop to exit.
Remember to include a space following each expression in a for statement. For more information, see the for statement in the ActionScript 2.0 Language Reference.
Flash CS3
Send me an e-mail when comments are added to this page | Comment Report
Current page: http://livedocs.adobe.com/flash/9.0/main/00000711.html