Possible Duplicate:
JavaScript for…in vs for
difference between for..in and for loops, and counter declaration
Is there any particular reason that for loops in arrays should be coded like for (var i = 0; i < foo.length; i++) { whereas loops in objects are just for (var i in foo) { Is it because of how objects are set up vs how arrays are set up? (I know arrays are a type of object btw) or just another nitpicky programming convention.
Well, the main reason is because
for...inonly iterate over defined members.So,
will only show the one value that is defined. Sometimes this is a good thing– usually not.
Also,
for...inloops over properties, not array indices (in javascript an array is just an a regular object with properties whose names are the values you assign to the array)So when you use for..in you can get weird results, like:
1
2
3
length
toString
etc.
Using the typical
forsyntax is just the better option for arrays. With objects, thefor...inmakes more sense, since the undefined issues don’t come up as often. Either way, I like to use thefor(var x; x < y; x++)syntax, though. It just feels better in js.