Is there any way to create Map data structure like java in java script?
That answer deals with `HashMap`, but that's not what Suvonkar asked about. In Java, a `Map` data structure is a set of key/value pairs, `HashMap` is a specific type of this that stores them in a special way for faster lookups.
R. Bemrose
2010-05-27 16:29:46
Please post dup links in comments, not as standalone answers.
Paul Sasik
2010-05-27 16:30:06
@R - Yes, Suvonkar said Map, but he also said "like in Java." In Java the vast majority of map implementations are based on HashMap, so I thought that article might be helpful. @Paul - Thanks for the tip, I will do that from now on, I did not know that's how it should have been handled.
Charlie Collins
2010-05-27 16:42:21
+2
A:
Yes, you can create a JS object and use properties as keys. E.g.
var map = {};
map.key1 = 'value1';
map.key2 = 'value2';
map['key3'] = 'value3';
alert(map.key1); // value1
alert(map['key2']); // value2
var key = 'key3';
alert(map[key]); // value3
It has much similarities with Javabeans and EL, if you know Java/JSP well.
BalusC
2010-05-27 16:23:34
A:
You could just create a named array.
var map = []; // Note that the brackets here are different than in Balus's answer
map['key1'] = 'value1';
map['key2'] = 'value2';
map['key3'] = 'value3';
alert(map['key1']);
alert(map['key2']);
var key = 'key3';
alert(map[key]);
I haven't compared the overhead of this as opposed to using a JavaScript object. I just assume it would be lower.
R. Bemrose
2010-05-27 16:38:38
The overhead should be the same, since an array in JavaScript is just an object that treats numeric keys a little differently.
Matthew Crumley
2010-05-27 17:17:27
There is no benefit in using an Array rather than an object here: you're not using any of Array's unique features, and there's not reason at all why it would be faster.
Tim Down
2010-05-27 22:43:07
A:
Unlike normal JavaScript objects, my jshashtable allows arbitrary keys and has a very similar API to Java's HashMap.
Tim Down
2010-05-27 22:39:20
BalusC: I didn't downvote all the other answers. I only downvoted R. Bemrose's answer, which was because it copied yours and added nothing valuable.
Tim Down
2010-05-27 23:14:14
Ah okay. It was just striking me that any answer expect yours was downvoted for no clear reason.
BalusC
2010-05-27 23:23:00
Possibly mine escaped downvote by not existing when all the others were downvoted.
Tim Down
2010-05-28 00:21:05