< Day Day Up >
Types of Loops
ActionScript can take advantage of three loop types, all of which perform an action (or
set of actions) while a specific condition is true.
while Loop
The syntax for creating this common type of loop is as follows:
while (someNumber < 10) {
// perform these actions
} The expression someNumber < 10 is the condition that determines the number of
iterations (passes through the statement) that the loop will perform. With each iteration,
the actions inside the loop are executed. The logic that determines how the condition is
evaluated (and how the loop is exited) is discussed shortly, in the section "Writing and
Understanding Loop Conditions."
Here's an example of the while loop:
while (myClip_mc._y < 0) {
myClip_mc._y += 3;
} This script moves the myClip_mc movie clip instance along the y axis until its position is
} This for loop duplicates myClip_mc 10 times.
for…in Loop
This loop is used to loop through all of an object's properties. Here's the syntax:
for (var i:String in someObject) {
trace(i);
} The i in the loop is a variable that, with each loop iteration, temporarily stores the name
of the property referenced by the variable. The value of i can be used in the actions within
the loop. For a practical application, consider the following script:
var car:Object = new Object();
car.color = "red";
car.make = "BMW";
car.doors = 2;
var result:String;
for (var i:String in car) {
"doors: 2
make: BMW
color: red" Because the car object has three properties, the for…in loop in this script will perform
only three iterations automatically.
NOTE
When you create a property on an object, it's stored in an associative array. In a regular
array, elements are referenced by number, starting with 0. In contrast, elements in an
associative array are referenced by name. The for…in loop in this section loops through
the associative array that contains all of these references in a specific timeline or object.
This type of loop has a variety of uses. You might use a for…in loop to find information,
for example, such as the following details:
•
Name and value of every variable in a timeline or object
•
Name of every object in a timeline or object
•
Name and value of every attribute in an XML document
< Day Day Up >