Skip to content Skip to sidebar Skip to footer

Problems With JavaScript "for In" Loop

I have an array of objects which will be the basis for a certain menu in my website. It will be build using JavaScript: [ {'menuName':'Contact Info','sectionName':'contacts'},

Solution 1:

for in iterates over object properties. Javascript arrays are just a specific kind of object with some handy properties to help you treat them as just arrays, but they still have internal object properties .. and you don't mean to iterate over these).

So, you shouldn't use for in to iterate over arrays. This only became evident to you when you added your background colour, but it'll always be the case.

Instead, loop with a counter and array .length.


Solution 2:

Your object gets methods and properties passed by JavaScript itself. Those are methods that every object gets when its created.

You have to use .hasOwnProperty to find only the properties and methods you assigned to the object!

for(var i in myObject){
  if(myObject.hasOwnProperty(i)){
    console.log(myObject.i);
  }
}

Hope that helps!

Here are two articles that helped me two understand it better:

http://bonsaiden.github.com/JavaScript-Garden/#object.hasownproperty http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/


Solution 3:

I see no difference between the two ways of iterating your data structure in this jsFiddle: http://jsfiddle.net/jfriend00/HqLdk/.

There are lots of good reasons why you should not use for (x in array) on arrays. The main reason is that that type of iteration iterates over the properties of the object, not just the array elements. Those properties can include other properties of the array if any have been added where as the for (var i = 0; i < array.length; i++) method will never have issues with added properties because by definition, it only iterates over the array elements.

It is somewhat luck that when no additional properties have been added to the array object, that iterating over the properties happens to include just the array elements. The language does not want you to iterate array elements that way. You should iterate arrays with

for (var i = 0; i < array.length; i++).

I understand the seduction of the simpler syntax, but it is not the right way to do it.


Post a Comment for "Problems With JavaScript "for In" Loop"