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), which lists both
named and numbered elements.
Creating and Referencing Named Array Elements
To add an element that can later be retrieved by name, we use the familiar square brackets, with a string instead of a number, on an existing array:
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 ...
Get ActionScript: The Definitive Guide 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.