Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is array both associative and indexed?

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.

like image 529
puffpio Avatar asked Jul 02 '09 20:07

puffpio


People also ask

What are index and associative arrays?

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.

Are all arrays in PHP associative?

PHP treats all arrays as associative, so there aren't any built in functions.

What do associative arrays used for indexes?

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.

What are the 3 types of arrays?

There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.


1 Answers

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.

like image 100
Alex Rozanski Avatar answered Sep 22 '22 19:09

Alex Rozanski