I will translate my original comment to a more detailed answer.
The indexes of arrays that are counted in .length go from 0 and up. Negative indexes are considered object properties, not array values. As you can see from the ECMAScript specification below, array indices are essentially just certain types of property values, given some special processing.
From section 15.4 of the ECMAScript specification :
15.4 Array Objects
Array objects provide a special approach to a specific class of property names. The name of the property P (as a String value) is the index of the array if and only if ToString (ToUint32 (P)) is equal to P and ToUint32 (P) is not equal to 2 ^ 32. A property whose property name is the index of the array is also called an element . Each Array object has a length property, the value of which is always a non-negative integer less than 2 ^ 32. The value of the length property is numerically greater than the name of each property whose name is an array index; when an Array object property is created or modified, other properties are adjusted as necessary to maintain this invariant. In particular, whenever a property is added whose name is the array index, the length property changes, if necessary, by one more than the numerical value of this array index; and whenever the length property changes, each property whose name is an index of an array whose value is not less than the new length is automatically deleted. This restriction applies only to the intrinsic properties of an Array object and does not depend on the properties of a length index or an array that can be inherited from its prototypes.
In addition, you should never โiterateโ arrays using an in-in-loop :
for (var i in a1)
Iterates over all enumerated properties of a1 , which will include all indexes of the array, but may also include other properties. If you want to iterate only the elements of an array with a for loop, you must use a different form:
for (var i = 0, len = a1.length; i < len; i++)
It prints a little more, but much safer.
Or in more modern browsers, you can use the .forEach() method.
jfriend00 Nov 11 2018-12-11T00: 00Z
source share