Is array both associative and indexed?

puffpio picture puffpio · Jul 2, 2009 · Viewed 65.9k times · Source

Can an array in JavaScript be associative AND indexed?

I'd like to be able to lookup an item in the array by its position or a key value.

Answer

Alex Rozanski picture Alex Rozanski · Jul 2, 2009

There are no such things as associative arrays in Javascript. You can use object literals, which look like associative arrays, but they have unordered properties. Regular Javascript arrays are based on integer indexes, and can't be associative.

For example, with this object:

var params = {
    foo: 1,
    bar: 0,
    other: 2
};

You can access properties from the object, for example:

params["foo"];

And you can also iterate over the object using the for...in statement:

for(var v in params) {
    //v is equal to the currently iterated property
}

However, there is no strict rule on the order of property iteration - two iterations of your object literal could return the properties in different orders.