For-In loops in JavaScript are really nice... until they aren't.
Sometimes the old-fashioned for loops are better for Arrays:
Not knowing exactly how they work might bite you. I'll start with an example:
var arr1 = ["a", "b", "c", "d"];Seems simple enough. What will be printed?
for(var i in arr1)
console.log(i, arr1[i], i+1, arr1[i+1]);
0 a 01 undefinedWhoops... I am an idiot! That's not exactly what I wanted. Note that i is a string, not a number. I wasted an hour of my life trying to figure out why i+1 was not working properly... only to come to this horribly obvious conclusion. It was totally worth a blog post... and a beer.
1 b 11 undefined
2 c 21 undefined
3 d 31 undefined
Sometimes the old-fashioned for loops are better for Arrays:
var arr1 = ["a", "b", "c", "d"];
for(var i = 0; i < arr1.length; i++)
console.log(i, arr1[i], i+1, arr1[i+1]);
Comments