user782400
user782400

Reputation: 1737

declare hashmap in javascript with <String,String array>

I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?

Upvotes: 3

Views: 5536

Answers (1)

Chris
Chris

Reputation: 7359

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']);

Upvotes: 3

Related Questions