Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript Recursive function seems to exit after first pass
    text
    copied!<p>I am trying to render a tree like hierarchy while recursing through set a nodes (<strong>index</strong>). I already know the roots(<strong>top</strong>). There are multiple root elements. I am trying to collect the entire html in the variable <strong>tree</strong> (this entire html will be appended to a div later)</p> <pre><code>tree = ""; top = ["1", "11", "14", "17", "72", "73", "74", "78", "79", "98", "99"]; index = { 1: { 'name': "Node 1", 'children': "2,3,4,5,6,7,8,9,10" }, 2: { 'name': "Node 2", 'children': "" }, //.... goes all the way upto 99 } </code></pre> <p>The recursive function makeFT(index,roots) only seems to break after traversing the children of first element in the "top" array. </p> <p>The code for this is at <a href="http://jsbin.com/ugoju4/2/edit" rel="nofollow">jsbin</a> and below. What could be the problem? Is there a better way to do this? Any help is appreciated.</p> <pre><code>makeFT(index, top); function makeFT(index, roots) { console.log(roots); tree == "" ? tree += '&lt;ul&gt;' : tree += '&lt;ul&gt;&lt;hr/&gt;' for (i = 0; i &lt; roots.length; ++i) { n = parseInt(roots[i]); //console.log(n); //console.log(index[n]); tree += '&lt;li&gt;' + roots[i] + '&lt;/span&gt;' + index[n].name; if (index[n].children === "") { tree += '&lt;input class="leaf tree-first-input" type="text" size="2"&gt;' } else { tree += '&lt;input class="non-leaf tree-first-input" type="text" size="2"&gt;' makeFT(index, index[n].children.split(",")); } tree += "&lt;/li&gt;" } tree += '&lt;/ul&gt;&lt;br/&gt;' } </code></pre> <p>UPDATE : Turns out this is a scoping problem and not a recursion problem. The recursion was alright. Since I did not define scope of the variable 'i' while looping through roots array, each subsequent recursed function inherited the value of unscoped 'i' thereby creating the problem. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload