Recipe 6.13 Reading Elements of an Associative Array
6.13.1 Problem
You want to enumerate the
elements of an
associative
array.
6.13.2 Solution
Use a for . . . in statement.
6.13.3 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]);
}
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
will not 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.
6.13.4 See Also
Recipe 6.2 and Recipe 7.10
|