以下のコードは、ポストオーダーをツリー内を走査します。呼び出し元のメソッドが特定の条件(後述_walkTree()
を参照)でfalseを返すときに、再帰を中断する予定です。再帰関数のブレーク
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);
})();
それがコールバックでfalse
に設定されています後continueWalk
フラグが戻っtrue
に戻りますなぜ私はとのトラブルを持っていることです。意図は、その時点でループを破る必要があり、上記の再帰関数からのすべてのループです。
このフィドルデモはそれを明確にする必要があります。https://jsfiddle.net/xuxuq172/2/
デバッガを使用しましたか? – Slavik
@Slavikありがとう、それは私が間違いがどこにあるかをわかった。 – Trace