Using for..in loops

Use the for..in statement to loop through (or iterate through) the children of a movie clip, properties of an object, or elements of an array. Children, referenced previously, include other movie clips, functions, objects, and variables. Common uses of the for..in loop include looping over instances on a timeline or looping over the key/value pairs within an object. Looping over objects can be an effective way to debug applications because it lets you see what data returns from web services or external documents such as text or XML files.

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 appear in an unpredictable order):

var myObj:Object = {x:20, y:30};
for (var i:String in myObj) {
    trace(i + ": " + myObj[i]);
}

This code outputs the following in the Output panel:

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) {
    trace(myArray[i]);
}

This code outputs the following in the Output panel:

three
two
one

For more information on objects and properties, see Object data type.

NOTE

You cannot iterate through the properties of an object if it is an instance of a custom class, unless the class is a dynamic class. Even with instances of dynamic classes, you are able to iterate only through properties that are added dynamically.

NOTE

The curly braces ({}) used to enclose the block of statements to be executed by the for..in statement are not necessary if only one statement executes.

The following example uses for..in to iterate over the properties of an object:

To create a for loop:

  1. Select File > New and then select Flash Document.
  2. Select Frame 1 of the Timeline, and then type the following ActionScript in the Actions panel:
    var myObj:Object = {name:"Tara", age:27, city:"San Francisco"};
    var i:String;
    for (i in myObj) {
      trace("myObj." + i + " = " + myObj[i]);
    }
    
  3. Select Control > Test Movie to test the code in Flash Player.

    When you test the SWF file, you should see the following text in the Output panel:

    myObj.name = Tara
    myObj.age = 27
    myObj.city = San Francisco
    

If you write a for..in loop in a class file (an external ActionScript file), instance members are not available within the loop, but static members are. However, if you write a for..in loop in a FLA file for an instance of the class, instance members are available but static members are not. For more information on writing class files, see Classes. For more information, see the for..in statement in the ActionScript 2.0 Language Reference.