Using nested loops in your ActionScript

The following example demonstrates how to make an array of objects and display each of the values in the nested structure. This example shows you how to use the for loop to loop through each item in the array and how to use the for..in loop to iterate through each key/value pair in the nested objects.

Nesting a loop within another loop:

  1. Create a new Flash document.
  2. Select File > Save As and name the document loops.fla.
  3. Add the following code to Frame 1 of the Timeline:
    var myArr:Array = new Array();
    myArr[0] = {name:"One", value:1};
    myArr[1] = {name:"Two", value:2};
    //
    var i:Number;
    var item:String;
    for (i = 0; i < myArr.length; i++) {
        trace(i);
        for (item in myArr[i]) {
            trace(item + ": " + myArr[i][item]);
        }
        trace("");
    }
    
  4. Select Control > Test Movie to test your code.

    The following is displayed in the Output panel.

    0
    name: One
    value: 1
    
    1
    name: Two
    value: 2
    

    You know how many items are in the array, so you can loop over each item using a simple for loop. Because each object in the array can have different name/value pairs, you can use a for..in loop to iterate over each value and display the results in the Output panel.