-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);
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • 2
    `for in loops` are for iterating over object members, [not for](http://stackoverflow.com/questions/500504/javascript-for-in-with-arrays) iterating over an array. Is the `.length` property ***really*** that much to deal with? – Matt Aug 07 '11 at 17:55
  • @Matt: i used to do foreach loops in PHP which were much faster to write than for and while. also, you won't have to deal with conflicting variables, counters, indexes using the foreach. i thought JS would be the same, until this happened. – Joseph Aug 07 '11 at 18:01