In the following code sample i get a strange behavior
var data = ['xxx', 'yyy'];
for (var i in data)
{
var a = i;
var b = data[i];
}
The two first iterations works just fine. I get index "0" and "1" in i, but then it loops one extra time and now the i is "sum". Is this by design or what is this extra iteration used for? The result in my case is always empty and it messes up my code. Is there a way to not do his extra loop?
BR
Andreas
You are looping through an
Array, not through anObject. For arrays it’s better to use:In your loop every property of the Array object is taken into account. That makes the
for ... inloop for array less predictable. In your case it looks likesumis a property (method) that’s added toArray.prototypeelsewhere in your code.There are more ways to loop through arrays. See for example this SO-question, or this one
Just for fun, a more esoteric way to loop an array: