递归函数中断

Recursive function break

本文关键字:中断 递归函数      更新时间:2023-09-26

下面的代码通过树进行订单后遍历。其目的是在调用方法在特定条件下返回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标志在回调设置为false后返回到true。其意图是,它应该在这一点上打破循环,以及上面递归函数中的所有循环。

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

您在此处覆盖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的内容,因为之前调用了一行。