所以我试图通过构建一个树类来练习 javascript。我在尝试递归获取树的叶子的函数中遇到了一些奇怪的问题。
例如,
function Tree(root, branches){
this.root = root;
this.branches = branches;
}
t = new Tree(2, [new Tree(6), new Tree(5)]);
Tree.prototype.is_leaf = function(){
return !(this.branches)
}
Tree.prototype.get_leaves = function(){
mainTree = this;
root = this.root;
branches = this.branches
list_of_leaves = []
if(mainTree.is_leaf()){
list_of_leaves.push(root);
} else {
for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
console.log(branches); //Branches logs correctly here
list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves());
/*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
console.log(branches); //Branches is set to undefined here
}
}
return list_of_leaves;
}
t.get_leaves();
当我尝试运行此函数时,出现“分支长度未定义”错误。由于某种原因,分支通过递归调用而发生变异,我不明白为什么会发生这种情况。数组中的 list_of_leaves 是否在所有实例之间共享?那么我应该将 get_leaves 定义为 Tree 对象中的方法而不是其原型(prototype)中的方法吗? (这样做似乎效率很低,所以我希望有更好的方法)。谢谢!
最佳答案
由于某种原因,您没有使用 var
进行变量声明,这会导致 branches
不是本地变量而是全局变量。对代码的快速修复是将 var
添加到 branches
中,如下所示:
function Tree(root, branches){
this.root = root;
this.branches = branches;
}
t = new Tree(2, [new Tree(6), new Tree(5)]);
Tree.prototype.is_leaf = function(){
return !(this.branches)
}
Tree.prototype.get_leaves = function(){
mainTree = this;
root = this.root;
var branches = this.branches; // <--- This line ;)
list_of_leaves = []
if(mainTree.is_leaf()){
list_of_leaves.push(root);
} else {
for(i = 0; i < branches.length; i++){ //go through each branch and run get_leaves
console.log(branches); //Branches logs correctly here
list_of_leaves.push.apply(list_of_leaves, branches[i].get_leaves());
/*extend the main list_of_leaves with the list of leaves of each branch (THIS LINE CAUSES THE PROBLEM)*/
console.log(branches); //Branches is set to undefined here
}
}
return list_of_leaves;
}
t.get_leaves();
关于JavaScript 数组递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206325/