PDA

View Full Version : Recursive function with for loop, for loop is breaking when calling itself



ciso
01-22-2011, 06:27 AM
Ok, I'm nearly pulling my hair out with this one. I have been looking at this code for two evenings now, and rewrote it 4 times already. It started out as jQuery code and now it's just concatenating strings together.

What I'm trying to do: Build a menu/outline using unordered lists from a multidimensional array.

What is happening: Inside the buildMenuHTML function, if I call buildMenuHTML, the for loop only happens once (i.e. only for 'i' having a value of '0'.) If I comment out the call to itself, it goes through the for loop all 3 times, but obviously the submenus are not created.

Here is the test object:


test = [
{
"name" : "Menu 1",
"url" : "menu1.html",
"submenu" : [
{
"name" : "menu 1 subitem 1",
"url" : "menu1subitem1.html"
},
{
"name" : "menu 1 subitem 2",
"url" : "menu1subitem2.html"
} ]
},
{
"name" : "Menu 2",
"url" : "menu2.html",
"submenu" : [
{
"name" : "menu 2subitem 1",
"url" : "menu2subitem1.html"
},
{
"name" : "menu 2subitem 1",
"url" : "menu2subitem1.html"
} ]
},
{
"name" : "Menu 3",
"url" : "menu3.html",
"submenu" : [
{
"name" : "menu 3 subitem 1",
"url" : "menu3subitem1.html"
},
{
"name" : "menu 3 subitem 1",
"url" : "menu3subitem1.html"
} ]
}
];


Here is the recursive function:


function buildMenuHTML(menuData,level) {
var ul;
if (level == 1) {
ul = "<ul id='menu'>";
} else {
ul = "<ul class='level" + level + "'>";
}

for (i = 0; i < menuData.length; i++) {
menuItemData = menuData[i];

ul += "<li>";
ul += "<a href='" + menuItemData.url + "'>" + menuItemData.name + "</a>";

if (typeof menuItemData.submenu != 'undefined') {
ul += buildMenuHTML(menuItemData.submenu,level + 1);
}

ul += "</li>";
}

ul += "</ul>";
return ul;
}


Here is how the function is called initially:


buildMenuHTML(test,1);


This is it's return value (with indentation added for readability):


<ul id='menu'>
<li><a href='menu1.html'>Menu 1</a>
<ul class='level2'>
<li><a href='menu1subitem1.html'>menu 1 subitem 1</a></li>
<li><a href='menu1subitem2.html'>menu 1 subitem 2</a></li>
</ul>
</li>
</ul>


'Menu 2' and 'Menu 3' don't show up! I'm sure it's something small that I'm overlooking, but any help would be appreciated.

venegal
01-22-2011, 06:45 AM
var ul, i;

You're not defining your counter — that makes it global, and the second call to buildMenuHTML overwrites it, so that it's out of bounds when execution gets back to the first call.

ciso
01-22-2011, 06:54 AM
var ul, i;

You're not defining your counter that makes it global, and the second call to buildMenuHTML overwrites it, so that it's out of bounds when execution gets back to the first call.

Oof. Thanks! :)