开发者

Associative arrays in Javascript?

Currently, I am creating a 3d array in js using the following:

var arr = [["name1", "place1", "data1"],
          [开发者_如何学Go"name2", "place2", "data2"],
          ["name3", "place3", "data3"]];

I can access each element using arr[0] or arr[1]. But is there anyways I can access them using a key like this: arr["name1"] should give me the first one. Any suggestions? I think I am looking for a Hashmap like functionality.


The situation has changed in the six 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 only way you could do that is by wrapping it in an object.

var arr = {
    name1 : ["name1", "place1", "data1"],
    name2 : ["name2", "place2", "data2"],
    name3 : ["name3", "place3", "data3"]
};


Javascript is a prototype based dynamic language. You can create objects and change their structure when you want.

var o = {name1: {place1: data1}, name2: {place2: data2}};

and access it with:

o.name1

The look-up implementation varies though and when you have a lot of properties that often changes this can be pretty slow (except in Chrome that uses a special scheme to access object properties i.e. embedded classes a-la-dynamic dispatch from smalltalk). Some libraries (e.g. MooTools) provide some hash map related structures,

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜