I am working on a website menu that will be created using JavaScript and an array of objects as the foundation:
[
{"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"}
]
To simplify my code, I decided to use a "for in loop" instead of dealing with indexes and lengths. I expected to see seven menu items displayed when the menu is built using <ul>
and <li>
.
However, while debugging, I accidentally added a background color to the <li>
element, which caused unexpected results. I noticed that there were more than 30 empty <li>
elements following the visible menu items.
This issue left me wondering why this unexpected behavior was occurring.
EDIT:
Here is the loop I used to create the menu items. This loop generates objects that another function will later parse. Each object represents an <li>
element with an <a>
element inside, containing properties from the initial array. Interestingly, when I switch from using a "for-in" loop to a regular for loop or while loop, the problem does not occur.
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);
}
}