I am learning Javascript. As a part of learning, I came across following scenario, where I expect the a1.length (the last line of the code) to show 201, but it shows 101, any Idea?
var a1 = new Array();
for (var i = -100; i<=100; i++)
a1[i] = i;
for (var i in a1)
{
document.write(i + "=" + a1[i])
document.write("<br>");
}
document.write(a1.length);
I’ll convert my original comment to a more thorough answer.
Array indexes that are counted in
.lengthgo from0and up. Negative indexes are considered properties of the object, not array values. As you can see from the ECMAScript spec below, array indexes are essentially just certain types of property values given some special treatment.From section 15.4 of the ECMAScript spec:
Also, you should never "iterate" arrays with a for-in-loop:
That iterates all enumerable properties of
a1which will include all array indexes, but could also include other properties. If you want to iterate only array elements with aforloop, you should use the other form:It is slightly more typing, but a lot safer.
Or, in more modern browsers, you can use the
.forEach()method.