Javascript Array with number as property name

var myArray = new Array(); myArray['112'] = 0; myArray.length 

Why is length 113 in the above example? Shouldn't '112' add an object property to the array and create something similar to myArray = {"112":0} ?

Also, why is the length 113 and not 1? Since myArray actually contains only 1 value

+6
source share
4 answers

Consider this simple example:

 var aa = []; aa[3] = 'three'; alert( aa.length // 4 + '\n' + aa[2] // undefined + '\n' + aa.hasOwnProperty('2') // false ); 

The number 3 is used to name the property, but it is converted to a string and used as the standard property name (ie, string "3").

Adding a property with the name "3" created one property and set the length to 4, since the length is always set to one more than the largest property value of a non-negative integer value.

No other property is created, the array is "sparse", that is, it does not have sequentially named (numbered) members. The for..in loop can also be used to see that there is only one property.

+1
source

The length array is one larger than the highest index, so you get 113 .

+4
source

Not. String '112' and pure numeric 112 evaluate the same thing when JS searches for an array, so you get a slot in the array, not a property.

The easiest way to think of JS Array indices is as properties, which are numbers, even in string form. This is more chameleon than you think at first.

But if you add a property with some odd name, for example myArray['foo'] , it will act as you expect, and the length will not change.

+2
source

You got an array of elements 0..112 - with a total length of 113 elements.

-2
source

Source: https://habr.com/ru/post/900576/


All Articles