I have following array/hashmap:
That's an Array
in JavaScript terms.
var arr = [];
console.log(arr.length); //Output: 0
That's expected, it's an empty array.
arr["1231321"] = "abcd";
console.log(arr.length); //Output: 1231322
The reason the length
property is so large as it's always +1
than the highest index. It doesn't matter that you used a string, keys for Array
s and Object
s are always strings in JavaScript.
The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.
Source
arr["1231321".toString()] = "abcd";
console.log(arr.length); //Output: 1231322
Calling toString()
on a string doesn't do anything (it's already a string).
arr["a1231321"] = "abcd";
console.log(arr.length); //Output: 0
Also expected, you set a property on the Array
which doesn't look like an index.
arr["1231321a"] = "abcd";
console.log(arr.length); //Output: 0
See above. There is no parsing internally of the string to try and get a number.
when I change my arr to var arr = {};
then it works.
That's how objects work in JavaScript. They're just a bucket of string keys to values.