SIMULATING ASSOCIATIVE ARRAYS

Course- Javascript >

In section “JAVASCRIPT ARRAYS,” we discussed the JavaScript array object and looked at its various properties and methods.

You may recall that the elements in JavaScript arrays have unique numeric identifiers:

var myArray = [];
myArray[0] = 'Monday';
myArray[1] = 'Tuesday';
myArray[2] = 'Wednesday';                 
                 

In many other programming languages, you can use textual keys to make the arrays more descriptive:

myArray["startDay"] = "Monday";

Unfortunately, JavaScript does not directly support such so-called associative arrays. However, using objects it is easy to go some way toward simulating their behavior. Using JSON notation makes the code easy to read and understand:

var conference = { "startDay" : "Monday",
"nextDay" : "Tuesday",
"endDay" : "Wednesday"
}                 
                 

You can now access the object properties as if the object were an associative array:

alert(conference["startDay"]); // outputs "Monday" This works because the two syntaxes object["property"] and object.property are equivalent in JavaScript.Remember that this is not really an associative array, although it looks like one. If you loop through the object, you will get, in addition to these three properties, any methods that have been assigned to the object.