Do you think there is a big difference in for...in and for loops? What kind of \"for\" do you prefer to use and why?
Let\'s say we have an array of associative array
Douglas Crockford recommends in JavaScript: The Good Parts (page 24) to avoid using the for in
statement.
If you use for in
to loop over property names in an object, the results are not ordered. Worse: You might get unexpected results; it includes members inherited from the prototype chain and the name of methods.
Everything but the properties can be filtered out with .hasOwnProperty
. This code sample does what you probably wanted originally:
for (var name in obj) {
if (Object.prototype.hasOwnProperty.call(obj, name)) {
// DO STUFF
}
}