Repeating actions using loops

ActionScript can repeat an action a specified number of times or while a specific condition exists. Loops let you repeat a series of statements when a particular condition is true. There are four types of loops in ActionScript: for loops, for..in loops, while loops, and do..while loops. Each type of loop behaves somewhat differently, and each one is useful for different purposes.

Most loops use some kind of counter to control how many times the loop executes. Each execution of a loop is called an iteration. You can declare a variable and write a statement that increases or decreases the variable each time the loop executes. In the for action, the counter and the statement that increments the counter are part of the action.

Loop

Description

for loops

Repeat an action using a built-in counter.

for..in loops

Iterate over the children of a movie clip or object.

while loops

Repeat an action while a condition exists.

do..while loops

Similar to while loops, except the expression evaluates at the bottom of the code block, so the loop always runs at least once.

The most common type of loop is the for loop, which loops over a block of code a predefined number of times. For example, if you have an array of items, and you want to perform a series of statements on each item in the array, you would use a for loop and loop from 0 to the number of items in the array. Another type of loop is the for..in loop, which can be very useful when you want to loop over each name/value pair within an object and then perform some type of action. This can be very useful when you are debugging your Flash projects and want to display the values that load from external sources, such as web services or external text/XML files. The final two types of loops (while and do..while) are useful when you want to loop over a series of statements but you don't necessarily know how many times you need to loop. In this case you can use a while loop that loops as long as a certain condition is true.

ActionScript can repeat an action a specified number of times or while a specific condition exists. Use the while, do..while, for, and for..in actions to create loops. This section contains general information on these loops. See the following procedures for more information on each of these loops.

To repeat an action while a condition exists:

To repeat an action using a built-in counter:

To loop through the children of a movie clip or an object:

For more information on each statement, see the individual sections that follow in this chapter, such as Using while loops, and their respective entries 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/00000709.html