问题在于 toString 函数内部,这并没有实现函数调用自己的范围:我需要一些东西来解决问题,'这'是javascript中最糟糕的,我已经在python中实现了确切的数据结构和函数,并且它有效...,我已经尝试过绑定和箭头函数,也许你可以帮我解决...代码的预期结果如下:
1
|__2
|__3
|__4
|__5
class Node {
constructor(data){
this.data = data;
this.parent = null;
this.children = [];
Node.nodes.push(this);
this.index = Node.nodes.length;
}
addChild(node){
node.parent = this;
this.children.push(node);
}
getLevel(){
let level = 0;
while(this.parent){
level+=1;
this.parent = this.parent.parent;
}
//console.log('lvl',level);
return level;
}
toString (){
// console.log('lvl',this.getLevel());
let prefix = " ".repeat(this.getLevel()*3);
prefix += this.getLevel()===0 ? "" :"|__";
console.log(prefix + this.index);
if(this.children){
for(let i = 0; i < this.children.length; i++){
this.children[i].toString();
}
}
}
pathToRoot(){
return 0;
}
}
Node.nodes = [];
const main = (()=>{
let root = new Node('root');
let kid1 = new Node('kid1');
let kid2 = new Node('kid2');
let kid3 = new Node('kid3');
let kid4 = new Node('kid4');
root.addChild(kid1);
kid1.addChild(kid2);
kid2.addChild(kid3);
kid3.addChild(kid4);
console.log('kid4 lvl :',kid4.getLevel())
root.toString(root);
})()
陪伴而非守候
郎朗坤
相关分类