About statements 155
To repeat an action using a built-in counter:
■ Use the for statement.
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.
In the following example, the first expression (
var i:Number = 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:Number = 4; i > 0; i--) {
myClip.duplicateMovieClip("newMC" + i, i, {_x:i*20, _y:i*20});
}
For more information on the for statement, see “Using for loops” on page 157.
To loop through the children of a movie clip or an 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:
var myObject:Object = {name:'Joe', age:25, city:'San Francisco'};
var propertyName:String;
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 might want your script to iterate over a particular type of child—for example, over
only movie clip children. You can do this using
for..in with the typeof operator. In the
following example, a child movie clip instance (called
instance2) is inside a movie clip
instance on the Stage. Add the following ActionScript to Frame 1 of the Timeline:
for (var myName in this) {
if (typeof (this[myName]) == "movieclip") {
trace("I have a movie clip child named " + myName);
}
}