Associative Arrays: The Arrays That Aren’t

I introduced associative arrays in Chapter 3. Unlike those just described, an associate array doesn’t have a numeric index, so you can’t access associative array elements using the following syntax:

assocArray[1]

Associative arrays can be created using the Array constructor, but this is considered bad form—primarily because you can’t access the array using numeric indexes. Instead, Object is normally used, and the array is automatically extended as new members are added:

var assocArray = new Object(  );
assocArray["one"] = "one";
assocArray["two"] = "two";

Unlike the traditional numeric arrays, associative array members can also be accessed directly on the object, as seen in many of the examples with the document, Math or Date objects, and so on:

document.writeln...
Math.ceil...

Associative arrays are used in the last few chapters, so I won’t get much further into the concept in this chapter. However, it is important to remember that when referencing a JavaScript Array, we usually mean the array that supports numeric indexing. Otherwise, we’ll usually use object or associative array to reference the object type.

Get Learning JavaScript 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.