Controlling when ActionScript runs 57
You can use the do..while statement to create the same kind of loop as a while loop. In a
do..while loop, the expression is evaluated at the bottom of the code block so the loop always
runs at least once, as shown in the following example:
i = 4;
do {
my_mc.duplicateMovieClip("newMC" +i, i );
i--;
} while (var i > 0);
To repeat an action using a built-in counter:
• Use the for statement.
Most loops use a counter of some kind 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. In the following example, the
first expression (
var i = 4) is the initial expression that is evaluated before the first iteration. The
second expression (
i > 0) is the condition that is checked each time before the loop runs. The
third expression (
i--) is called the post expression and is evaluated each time after the loop runs.
for (var i = 4; i > 0; i--){
myMC.duplicateMovieClip("newMC" + i, i + 10);
}
To loop through the children of a movie clip or object:
• Use the for..in statement.
Children include other movie clips, functions, objects, and variables. The following example uses
the
trace statement to print its results in the Output panel:
myObject = { name:'Joe', age:25, city:'San Francisco' };
for (propertyName in myObject) {
trace("myObject has the property: " + propertyName + ", with the value: " +
myObject[propertyName]);
}
This example produces the following results in the Output panel:
myObject has the property: name, with the value: Joe
myObject has the property: age, with the value: 25
myObject has the property: city, with the value: San Francisco
You may want your script to iterate over a particular type of child—for example, over only movie
clip children. You can do this with
for..in in conjunction with the typeof operator.
for (name in myMovieClip) {
if (typeof (myMovieClip[name]) == "movieclip") {
trace("I have a movie clip child named " + name);
}
}
For more information on each action, see individual entries in Chapter 12, “ActionScript
Dictionary,” on page 205.