Click to See Complete Forum and Search --> : What is wrong with this function


justin001
10-07-2003, 08:17 AM
Trying to make a recursive function to continue creating DIVs for nested arrays. What am I doing wrong here. I appreciate and all help...




<html>
<head>
<script language="javascript">
var menuArray=
[
"One",
["Two","Three",["Four","Five",["Six"]]],
"Seven",
"Eight"
]

function createMenus(pArray)
{
var content="<div>";
for (var i=0;i<pArray.length;i++)
{if (pArray[i].length) createMenus(pArray[i]);
else content+=pArray[i]+"<br>"};
content+="</div>";
return content;
}

</script>
<style type="text/css">
<!--
body {cursor: default;}
.menuContainer {position: absolute;border: 1px solid black;background-color: white;padding: 10px;}
-->
</style>
</head>
<body id="myBody">
<script>document.write(createMenus(menuArray));</script>
</body>
</html>

Gollum
10-07-2003, 08:30 AM
Your problem is that Array is not the only class that has a property of "length", String does too!
Change your createMenus function like this...

function createMenus(pArray)
{
var content="<div>";
for (var i=0;i<pArray.length;i++)
{
if (pArray[i] instanceof Array) content+=createMenus(pArray[i]);
else content+=pArray[i]+"<br>";
}
content+="</div>";
return content;
}

justin001
10-07-2003, 08:34 AM
Gollum! Thank-you! I don't know how I missed that!

Thanks a stack for the help!