Previous Page
Next Page

Recipe 5.16. Reading Elements of an Associative Array

Problem

You want to loop through the elements of an associative array.

Solution

Use a for . . . in statement.

Discussion

You iterate through the elements of integer-indexed arrays by using a for statement. However, named elements in associative arrays cannot be accessed by a numeric index, and the order of associative array elements is not guaranteed, regardless of the order in which the elements are added to the array. For that reason, there are also no methods to sort or reverse an associative array, or otherwise change its order.

Fortunately, you can loop through the enumerable elements of an associative array by using a for . . . in statement. This statement iterates through all the readable properties of the specified object. The syntax for a for . . . in statement is as follows:

for (key in object) {
    // Actions
}

The for . . . in statement doesn't require an explicit update statement because the number of loop iterations is determined by the number of properties in the object being examined. Note that key is a variable name that will be used to store the property name during each iteration, not the name of a specific property or key. On the other hand, object is the specific object whose properties you want to read. For example:

var members:Object = new Object(  );
members.scribe = "Franklin";
members.chairperson = "Gina";
members.treasurer = "Sindhu";
     
// Use a for . . . in statement to loop through all elements.
for (var sRole:String in members) {
    // Displays:
    // treasurer: Sindhu
    // chairperson: Gina
    // scribe: Franklin
    trace(sRole + ": " + members[sRole]);
}

When you use a for . . . in statement, you must use array-access notation (square brackets) with the associative array. If you try to use property notation (with the dot operator) it won't work properly. This is because the value that is assigned to the key iterator variable is the string name of the key, not the key's identifier.

A for . . . in loop does not display all built-in properties of an object. For example, it displays custom properties added at runtime, but it does not enumerate methods of built-in objects, even though they are stored in object properties.

See Also

Recipe 5.2


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)