JavaScript Associative Arrays
We saw how to use numerical indexes to reference array elements inside one-dimensional and multidimensional JavaScript arrays. By playing on the object-based aspect of the language, it is possible to create custom indexes on the fly, and use them to reference array elements as if they were object properties.
Create an Associative Array in JavaScript
In the script below, we create the basis for a Acronym Lookup program in JavaScript. We will use an associative array to reference the meaning of each acronym, and use the acronym as the associative array's index:
// Declare a regular JavaScript array
var arlene = new Array();
// Now make it an asssociative array
arlene["CSS" ] = "Cascading Style Sheets";
arlene["HTML"] = "HyperText Markup Language";
arlene["W3C" ] = "World Wide Web Consortium";
// Get the meaning of the "CSS" acronym
alert( arlene["CSS"] );
The final line of JavaScript code produces the following result:
Associative Arrays and JavaScript Object Properties
Associative arrays in JavaScript are equivalent to declaring object properties on the fly (rather, properties of object instances, if you do not use the prototype property.) Conversely, values of built-in object properties can be called as associative array elements.
var arlene = new Array("first", "second", "last");
// Retrieve the array length as an associative array element:
alert( arlene["length"] );
The script above treats the built-in Array object's length property as an associative array element. The actual array dimension was returned:
The reverse holds true: the script below declares an associative array element, and then retrieves its value as an instance property, using "dot notation".
var arlene = new Array();
// Declare an associative array element:
arlene["CSS"] = "Cascading Style Sheets";
// Retrieve the value using dot notation:
alert( arlene.CSS );
Predictably, our script returned the same result as the associative array notation used earlier, using the arlene["CSS"] syntax.
Associative arrays are tightly related to the ability JavaScript offers to create properties on-the-fly for objects or instances of objects.