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 (keyinobject) { // 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]); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access