Creating indexed arrays

Indexed arrays store a series of one or more values. You can look up items by their position in the array, which you might have done in earlier sections. The first index is always the number 0, and the index increments by one for each subsequent element that you add to the array. You can create an indexed array by calling the Array class constructor or by initializing the array with an array literal. You create arrays using the Array constructor and an array literal in the next example.

To create an indexed array:

  1. Create a new Flash document, and save it as indexArray.fla.
  2. Add the following ActionScript to Frame 1 of the Timeline:
    var myArray:Array = new Array();
    myArray.push("one");
    myArray.push("two");
    myArray.push("three");
    trace(myArray); // one,two,three
    

    In the first line of ActionScript, you define a new array to hold the values.

  3. Select Control > Test Movie to test your code.

    The following text is displayed in the Output panel:

    one,two,three
    
  4. Return to the authoring tool, and delete the code in the Actions panel.
  5. Add the following ActionScript to Frame 1 of the Timeline:
    var myArray:Array = ["one", "two", "three"];
    trace(myArray); // one,two,three
    

    In this code you use the array literal to define a new array for your code. This code is the equivalent of the ActionScript you wrote in step 2. When you test the code, you see the same output appear in the Output panel.