Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array reserves so many spaces even with string key?

I have following array:

var arr = [];
console.log(arr.length); //Output: 0

arr["1231321"] = "abcd";
console.log(arr.length); //Output: 1231322

arr["1231321".toString()] = "abcd";
console.log(arr.length); //Output: 1231322

arr["a1231321"] = "abcd";
console.log(arr.length); //Output: 0

arr["1231321a"] = "abcd";
console.log(arr.length); //Output: 0

Here is the Fiddle: http://jsfiddle.net/HcrcR/

when I change my arr to var arr = {}; then it works.

but what is the reason of it even if I use string key it starts pushing the data from key?

like image 242
Vural Avatar asked Nov 24 '25 14:11

Vural


1 Answers

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 Arrays and Objects 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.

like image 58
alex Avatar answered Nov 27 '25 05:11

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!