递归函数中断

时间:2016-05-16 15:23:28

标签: javascript recursion tree

下面的代码通过树进行后序遍历。目的是在某个条件下调用方法返回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); 
})(); 

我遇到的问题是continueWalk标志在被回调设置为true后返回false的原因。目的是它应该在那一点打破循环,并从上面的递归函数中循环。

这个小提琴演示应该清楚明确:https://jsfiddle.net/xuxuq172/2/

1 个答案:

答案 0 :(得分: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前一次呼叫的内容。