开发者

Does Javascript have associative arrays?

Does Javascript have associative arrays? Please e开发者_JS百科xplain.


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.


This answer is pretty much a copy-paste of my previous answer on this question.

The situation has changed in the five years since this question was asked.

Due to weak typing associative arrays can be faked in JavaScript:

>> var names = new Array();
undefined

>> names["first"] = "Dotan";
"Dotan"

>> names["last"] = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

That is sometimes useful, and all browsers released since 2012 support it, but there are caveats! The array cannot be simply read back:

>> names
Array [  ]

More importantly, the array's length cannot be easily retrieved:

>> names.length
0

Therefore this is not an associative array in the sense that JavaScript would have supported it had it been intended, but rather a workaround that is often useful if for whatever reason a real JS object does not support what you need:

>> var names = {};
undefined

>> names.first = "Dotan";
"Dotan"

>> names.last = "Cohen";
"Cohen"

>> for ( key in names ) { console.log(key+" "+names[key]) }
undefined
first Dotan
last Cohen

>> names
Object { first: "Dotan", last: "Cohen" }

>> Object.keys(names).length
2


The closest we have is an object; the easiest way you can define this is using object literal syntax.

var assocArray = {
   key: 1,
   key2: 2
};

You should be wary of a few things however:

  1. It does not have a .length property.
  2. You should use for in to iterative over it, rather than for(;;;);, but should combine it with hasOwnProperty():

    for (var x in assocArray) {
        if (assocArray.hasOwnProperty(x)) {
            // x = the key, assocArray[x] = the value 
        }
    }
    
  3. There is no concept of ordering/ sorting the members. Whilst all implementations I know of iterate the members in the order they were added, this is not standardised.


Instead of associative arrays. Javascript has objects. Properties of an object are addressed using a string.

 var obj1 = {};  // declare empty object
 var obj2 = {a: 1, b: 'string', c: [4,5]}; // obj with 3 properties, a, b, and c
        // note that the 'c' property contains an anonymous array 

 alert(obj2.a); // shows 1
 obj2.a = 'another string'; // redefine the 'a' property
 obj2.cookie = 'oatmeal'; // add a new property to the object
 obj2['ice_cream'] = {vendor: 'Beyers', 
                      flavor: 'Chocolate Surprise'}; // add anonymous object as
                           // a new property for the object

 assert(obj2.a === obj2['a']); // two ways to retrieve the value
 var i = 'a'; // using an index varable
 assert(obj2.a === obj2[i]);  // note the i does not have apostrophes around it

See the Quirksmode docs


Something comparable in JavaScript is an object.

var my_obj = { key : 'value' } 


Sure it does (kind of, use objects)

var foo = {
      bar: "hello"
}

accessible with

foo.bar
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜