2016-05-16 48 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