O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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]); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required