6.13. Reading Elements of an Associative Array

Problem

You want to enumerate the elements of an associative array.

Solution

Use a for . . . in statement.

Discussion

You can iterate through the elements of integer-indexed arrays 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.

Fortunately, you can loop through the enumerable elements of an associative array using a for . . . in statement. That is, a for . . . in 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:

members = new Object(  );
members.scribe = "Franklin";
members.chairperson = "Gina";
members.treasurer = "Sindhu";

// Use a for . . . in statement to loop through all the elements. for (var role in members) { // Outputs: // treasurer: Sindhu // chairperson: Gina // scribe: Franklin trace(role + ": " + members[role]); ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.