为什么循环里面的递归函数在javascript中没有完成

时间:2014-06-21 20:21:55

标签: javascript function loops recursion tree

我需要: 检查树中的每个节点从根开始,在其节点上循环,检查每个节点是否有与该节点相关的子节点并再次调用相同的函数(递归函数)。 我的代码是:


var tree = new Array();

tree[0] = ["Node1", "Node2", "Node3", "Node4"] 
tree[1] = ["Node1", "Node2"] 
tree[2] = ["Node1", "Node2", "Node4"] 


function schTree(treeArr){
 //LOOP ON CHILD NODE TO CHECK IF THE NODE IS PARANT FOR SOME OTHER NODE OR NOT and do some actions 
     for(i=0;i<treeArr.length; i++){

                if(treeArr[i].length){
                     schTree(treeArr[i]);
                  };
      }
  }

//call search tree function 
schTree(tree);    

问题是: 如果我回想起这个功能,那么循环就没有完成。

我认为每个函数都递归调用它在当前函数之上构造新函数(在内存中的同一个地方工作而不创建新函数)

如何: 使正常的递归函数?????

提前致谢

Maged Rawash

2 个答案:

答案 0 :(得分:0)

您检查它的方式不起作用,因为字母的.length1,因此您将获得通过tree,{{1 },tree[0],然后无限地传入tree[0][0],直到堆栈变得太大而你得到tree[0][0][0]。相反,这样做:

RangeError

答案 1 :(得分:0)

您只收到第一个节点,因为您声明了没有关键字var

的for循环

for(i=0;i<treeArr.length; i++) 到遍历第一个节点数组时,i等于3

以下是我对其余代码的评论

var tree = [];
tree[0] = ["Node1", "Node2", "Node3", "Node4"] 
tree[1] = ["Node5", "Node6"] 
tree[2] = ["Node7", "Node8", "Node9"] 

//recursive function that checks if a node 
function schTree(treeArr){

    //FIX A
    //find out if element is an array
    if(Array.isArray(treeArr)){

    //FIX B
    //You did not declare i with var, meaning each recursive call
    //carried the prior value of i with it.
    //so after iterating over the first node, i = 3
    //which is greater than the length of node 1 and 2
     for(var i=0;i<treeArr.length; i++){

            //FIX C
            //removed inner length check, not needed
            //schTree checks for array before getting to this
            //point
             schTree(treeArr[i]);
      }
    }
    else {
        //While you'd probably want to do a clause for
        //objects, we'll assume only arrays here.

        //FIX D
        //Do something with the non array element
        console.log(treeArr);
    }
  }
  schTree(tree);