Unlike PHP (and many other languages), JavaScript doesn't support associative arrays. Period. It does support objects, which can be used somewhat like an associative array, but without a lot of the usual array goodness. It's an imperfect world, and it bugs me all the time, but it's just the way it is.
In JS, you can set up an array like so:
var myArray = new Array(); myArray[0] = 'David'; myArray[1] = 'Jones';
But you can't do:
var myArray = new Array(); myArray['firstname'] = 'David'; // not possible in JS myArray['lastname'] = 'Jones'; // not possible in JS
That's because JavaScript doesn't support the associative (e.g. 'firstname'
) index. It only a numerical index (e.g. [0]
).
However, you can create an object and assign arbitrarily named properties to it:
var myObject = new Object(); myObject.firstname = 'David'; myObject.lastname = 'Jones'; // alternately, use the shorthand syntax: var myObject2 = {firstname: 'David', lastname: 'Jones'};
You can access properties of this object with either the dot (myObject.firstname
) or array (myObject['firstname']
) notation. You can iterate over all its properties with a for…in loop:
for (var index in myObject) { document.write ('key: ' + index + '; value: ' + myObject[index] + ' '); }
The only thing you can't do is use the array functions, such as join()
and splice()
. Those only work on true Arrays, which were created with the Array constructor and have numerical indexes.