User Guide
88 ActionScript Language and Syntax
Looping
Looping statements allow you to perform a specific block of code repeatedly using a series of
values or variables. Adobe recommends that you always enclose the block of code in braces
(
{}). Although you can omit the braces if the block of code contains only one statement, this
practice is not recommended for the same reason that it is not recommended for conditionals:
it increases the likelihood that statements added later will be inadvertently excluded from the
block of code. If you later add a statement that you want to include in the block of code, but
forget to add the necessary braces, the statement will not be executed as part of the loop.
for
The for loop allows you to iterate through a variable for a specific range of values. You must
supply three expressions in 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 will be the numbers 0 through
4, each on its own line.
var i:int;
for (i = 0; i < 5; i++)
{
trace(i);
}
for..in
The for..in loop iterates through the properties of an object, or the elements of an array. For
example, you can use a
for..in loop to iterate through the properties of a generic object
(object properties are not kept in any particular order, so properties may appear in a seemingly
random order):
var myObj:Object = {x:20, y:30};
for (var i:String in myObj)
{
trace(i + ": " + myObj[i]);
}
// output:
// x: 20
// y: 30
You can also iterate through the elements of an array:
var myArray:Array = ["one", "two", "three"];
for (var i:String in myArray)