11.6. Named Array Elements
Elements are usually numbered but can also be named. Using named elements we can emulate so-called associative arrays or hashes. Note that named array elements cannot be manipulated by the Array methods ( push( ), pop( ), etc., covered later) and are not considered part of the numbered element list. An array with one named element and two numbered elements will have a length of 2, not 3. To access all the named elements in an array, therefore, we must use a for-in loop (discussed in Chapter 8, "Loop Statements"), which lists both named and numbered elements.
11.6.1. Creating and Referencing Named Array Elements
arrayName[elementName] = expression
where elementName is a string. For example:
var importantDates = new Array( ); importantDates["dadsBirthday"] = "June 1"; importantDates["mumsBirthday"] = "January 16";
We may also use the dot operator, as follows:
arrayName.elementName = expression
In this case, elementName must be an identifier, not a string. For example:
var importantDates = new Array( ); importantDates.dadsBirthday = "June 1"; importantDates.mumsBirthday = "January 16";
Assuming that we know an element's identifier (for example, dadsBirthday in the importantDates array), we can access it in one of two ways:
var goShopping = importantDates["dadsBirthday"]; var goShopping = importantDates.dadsBirthday;
Just as is the case when assigning a value to a named element, when accessing an element with square brackets, elementName must be a string or an expression that yields a string. Likewise, when used with the dot operator, elementName must be an identifier (i.e., the element's name without quotes), not a string.
11.6.2. Removing Named Elements
To rid an array of an unwanted named element, we use the delete operator, which was introduced in Chapter 5, "Operators":
Deleting a named element destroys both the element value and the element container, freeing up any memory being occupied by the element and its contents. (Contrast this with the delete operator's behavior for numbered elements, where it simply clears the value but leaves the container intact.)
Copyright © 2002 O'Reilly & Associates. All rights reserved.