Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript have associative arrays?

Tags:

javascript

Does Javascript have associative arrays? Please explain.

like image 783
Imran Avatar asked Oct 06 '11 13:10

Imran


1 Answers

Nope; JavaScript arrays are just numeric keys and mixed values. The same thing can be achieved (or, actually, it's exactly the same as associative arrays in other languages) with objects:

var foo = {
  a: 123,
  b: 'CDE'
};

foo.a; // 123
foo['a']; // 123

You could use arrays:

var foo = [];
foo.a = 123;
foo.b = 'CDE';

foo.b; // CDE
foo['b']; // CDE

HOWEVER, this should never be done because this will not enter the key/value pairs into the array, but add them to the array object as properties. (besides, {a: 123} is easier than a = []; a.a = 123) If you need key/value pairs, use Objects. If you need an enumerated list, use arrays.

like image 181
goto-bus-stop Avatar answered Sep 27 '22 17:09

goto-bus-stop