[英]Javascript: Recursion with for loop
我对当前的递归有问题。 当我记录 this.memb 和 this.child 时,这两个是相同的值。 然而,这不应该是一个案例。 this.child 理论上应该是 this.memb 的孩子。
buildGraphNode(treeNode){
if(!(treeNode.data instanceof Array)){
this.memb = this.member("" + treeNode.label, "" + treeNode.label, 'images/user1.png', '#d0000c', '', 'B');
this.members.push(this.memb);
}
for (var i = 0; i<treeNode.children.length; i++) {
this.child = this.buildGraphNode(treeNode.children[i]);
if(this.child != null && this.memb !=null){
console.log(this.memb);
console.log(this.child);
this.connections.push(this.link(this.memb,this.child));
}
}
return this.memb;
}
您对“this”使用了过多的引用。 您在这里操作同一个this
对象,这最终会修改外部上下文。 尝试使用局部变量:
buildGraphNode(treeNode){
if(!(treeNode.data instanceof Array)){
var memb = this.member("" + treeNode.label, "" + treeNode.label, 'images/user1.png', '#d0000c', '', 'B');
this.members.push(memb);
}
for (var i = 0; i<treeNode.children.length; i++) {
var child = this.buildGraphNode(treeNode.children[i]);
if(child != null && memb !=null){
console.log(memb);
console.log(child);
this.connections.push(link(memb,child));
}
}
return memb;
}
我不知道您是如何构建代码的,因此可能需要更改其他出现的this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.