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.
There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables.
PHP treats all arrays as associative, so there aren't any built in functions.
Associative arrays differ from normal, fixed-size arrays in that they have no predefined limit on the number of elements, the elements can be indexed by any tuple as opposed to just using integers as keys, and the elements are not stored in preallocated consecutive storage locations.
There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With