I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?
1 Answer
If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);
2 Comments
Marcel Korpel
You'd better use
var arr = {};Marcel Korpel
You'd better not use
new Object(), it's not as optimized as {} (I know, micro-optimizations are not worth the hassle) and someone might have overridden Object.