2016-05-16 47 views
1

下面的代码通过树进行后序遍历。打算在某种情况下调用方法返回false时中断递归(请参见下面的_walkTree())。递归函数中断

function _walkPostOrder(tree, callback, ctx){ 
    var continueWalk = true; 

    function _walk(tree, callback, ctx, parent){ 
     for(var idx = 0, length = tree.length; idx < length; idx++){ 
      console.log(continueWalk); 
      if(continueWalk) { 
       var node = tree[idx]; 
       if(node.children && node.children.length > 0 && continueWalk) 
        _walk.call(this, node.children, callback, ctx, node); 
       continueWalk = callback.call(ctx, node, parent, tree, idx); 
       continue; 
      }; 
      console.log(node); 
      break; 
     }; 
    } 
    _walk(tree, callback, ctx); 
} 

var json = [{ text: "root", children: [ 
    {id: "id_1", text: "node_1", children:[ 
     {id: "id_c1", text: "node_c1"}, 
     {id: "id_c2", text: "node_c2", children: [ 
      {id: "id_c2_c1", text: "node_c2_c1"}, 
      {id: "id_c2_c2", text: "node_c2_c2"}, 
      {id: "id_c2_c3", text: "node_c2_c3"}]}, 
     {id: "id_c3", text: "node_c3"}]}, 
    {id: "id_2", text: "node_2"}]}]; 

//Iterate 
(function _walkTree(){ 
    _walkPostOrder.call(this, json, function(node, parentNode, siblings, idx){ 
     console.log(node.id); 
     if(node.id == "id_c2_c2") return false; 
     return true; 
    }, this); 
})(); 

我有麻烦就是为什么之后,它已经由回调设置为falsecontinueWalk标志返回到true。其意图是它应该打破这一点的循环,以及上面递归函数中的所有循环。

这拨弄演示应该清楚:https://jsfiddle.net/xuxuq172/2/

+0

你使用调试器吗? – Slavik

+0

@Slavik谢谢,这就是我弄清楚错误在哪里。 – Trace

回答

1

要覆盖continueWalk这里:

if(node.children && node.children.length > 0 && continueWalk) 
    _walk.call(this, node.children, callback, ctx, node); 
continueWalk = callback.call(ctx, node, parent, tree, idx); 
// ^^^^^^^^^^ 

您需要检查的continueWalk内容与之前的结果之前调用线。

+1

Ouf我现在看到它。谢谢妮娜! – Trace