3

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

1 Answer 1

3

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']);
Sign up to request clarification or add additional context in comments.

2 Comments

You'd better use var arr = {};
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.