I am coding in javascript & I need HashMap type structure .
Normally when I need hashmaps , I would use associative arrays only (with strings as keys).
But this time I need integers as keys to hashmaps.
So if I try to store A[1000]=obj, 1001 sized array is created & A[1001] is put as obj.
Even if I try A[“1000”]=obj , it still allocates 1001 spaces & fills them with undefined.
I dont want that as my keys could be very large ( around 1 mill).
I could use it as A[“dummy1000”]=obj but I dont want to use this dirty method.
Anyway of doing it elegantly & with ease too ?
Doing
A[1000] = 1doesn’t create an array with 1000 elements. It creates an array object whose length attribute is 1001, but this is only because the length attribute in JavaScript arrays is defined as the maximum index + 1.The reason it works like this is so you can do
for(var i = 0; i < A.length; i++).I see you’re confused about the allocation of the array. To you it looks like JavaScript has filled the elements with undefined – actually there isn’t anything there, but if you try to access any element in an array that hasn’t been defined you get
undefined.