174 Syntax and Language Fundamentals
To create an associative array using an Object constructor:
1. Create a new Flash document, and save it as assocArray.fla.
2. Add the following ActionScript to Frame 1 of the Timeline:
var monitorInfo:Object = {type:"Flat Panel", resolution:"1600 x 1200"};
trace(monitorInfo["type"] + ", " + monitorInfo["resolution"]);
This code creates an associative array called monitorInfo, and uses an object literal to
initialize the array with two key/value pairs.
var monitorInfo:Object = new Object();
3.
Select Control > Test Movie.
The Output panel displays the following text:
Flat Panel, 1600 x 1200
4.
Add the following ActionScript to Frame 1 of the Timeline, following the code you entered
previously:
monitorInfo["aspectRatio"] = "16:10";
monitorInfo.colors = "16.7 million";
trace(monitorInfo["aspectRatio"] + ", " + monitorInfo.colors);
After you use using either an object literal or the Object class constructor to create the
array, you can add new values to the array using either the bracket operator (
[]) or the dot
operator (
.), as demonstrated in this code. The code you just typed adds two new values
to
monitorInfo array.
5. Select Control > Test Movie.
The Output panel displays the following text:
16:10, 16.7 million
Note that a key can contain a space character. This is possible with the bracket operator,
but generates an error if you attempt this with the dot operator. Using spaces in your key
names is not recommended. For more information on bracket operators and dot
operators, see “About operators” on page 176. For more information on well-formatted
code, see “Formatting ActionScript syntax” on page 764.
NOTE
If you do not need to initialize the array at declaration time, you can use the Object
constructor to create the array: