-1

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"},
  {"menuName":"Facilities","sectionName":"facilities"},
  {"menuName":"Locations","sectionName":"locations"},
  {"menuName":"Packages","sectionName":"packages"},
  {"menuName":"Policies","sectionName":"policies"},
  {"menuName":"Reviews","sectionName":"reviews"},
  {"menuName":"Rooms","sectionName":"rooms"}
]

So I decided to use the "for in loop" so that I won't have to deal with indexes and lengths. I expect seven items to appear in the menu when it gets built (I'll be using <ul> and <li>).

When I was debugging and accidentally added a background color to the <li>, is when all hell broke loose. I found at least 30 empty <li> after the visible 7th menu <li>.

Why is this happening?

EDIT:

Here's the loop. The loop creates another object for another function to parse later on. (It creates an <li> with an <a> inside with properties provided by the previous array.) I know that the other function works fine because when I change this "for-in" loop to an ordinary for loop, or while loop, it works fine.

this.sectionList = function(menu, id) {
    var list = new Array();

    for(var i in menu) {
        var listItem = {
            "element" : "li",
            "contains" : [{
                "element" : "a",
                "attr" : {
                    "href" : menu[i].sectionName + ':' + id
                },
                "contains" : menu[i].menuName
            }]
        }
        list.push(listItem);
    }
}
6
  • 2
    who knows? could you show what you are doing with the code you have. Commented Aug 7, 2011 at 17:48
  • 1
    Could you paste your loop code in please? Commented Aug 7, 2011 at 17:48
  • How did you add background color? Commented Aug 7, 2011 at 17:48
  • My ESP isn't working today. Please actually explain your issue. There is no <li>-generating code in your question, and you should not be iterating over arrays with for in. Commented Aug 7, 2011 at 17:52
  • 2
    for in loops are for iterating over object members, not for iterating over an array. Is the .length property really that much to deal with? Commented Aug 7, 2011 at 17:55

3 Answers 3

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What about sparse arrays? var arr = []; arr[1236345566] = 10; arr[2745453222] = 30; var sum = 0; for (var i = 0, len = arr.length; i < len; ++i) { sum += Number(arr[i]); } would be rather slow. This is a contrived example, but there are plenty of cases where you might need to do real work on all the members of a sparse array.
@kpozin: It would, but that's only because this is not what Array is for.
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/

7 Comments

Don't do this. Loop properly instead.
This is not how to loop over arrays.
Yeah. But it's how to loop over objects isn't it? I thought he had two loops, one for the array itself and one for the objects inside of it.
@dotweb: i suppose you have answered my question (even without the additional info). i never knew the for-in would also run through the prototype of the object.
@dotweb: Yes, but he's looping over the array. And begging for accepts when there is some controversy over the answer seems a little raw...
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.