我有这段代码:
function Tree() {
this.capacity = 1;
this.contents = 0;
this.children = [];
this.divided = false;
this.pour = function(amount) {
this.contents += amount;
if (this.contents <= 1) {
return;
}
if (!this.divided) {
this.divide();
}
amount = this.contents - 1;
this.contents = 1;
for (let child in this.children) {
this.children[child].pour(amount * .5);
}
}
this.divide = function() {
this.children = new Array(2).fill(0).map(x => new Tree());
this.divided = true;
return;
}
this.getContents = function(row, currentRow) {
if (currentRow === undefined) {
currentRow = 0;
}
if (row === currentRow) {
console.log('Contents:', this.contents)
return this.contents;
}
if (this.divided) {
console.log(row, currentRow)
currentRow++;
this.children[0].getContents(row, currentRow);
} else {
return;
}
}
}
创建一棵树,倒入其中,并使用以下内容获取其内容:
let tree = new Tree();
tree.pour(10);
tree.getContents(1);
它应返回1,因为第二行内容为1.它在控制台中记录1,但不返回正确的值。我很好奇出了什么问题。
编辑:我看着将它切换到一个类并且它没有解决问题:
class Tree {
constructor() {
this.capacity = 1;
this.contents = 0;
this.children = [];
this.divided = false;
}
pour(amount) {
this.contents += amount;
if (this.contents <= 1) {
return;
}
if (!this.divided) {
this.divide();
}
amount = this.contents - 1;
this.contents = 1;
for (let child in this.children) {
this.children[child].pour(amount * .5);
}
}
divide() {
this.children = new Array(2).fill(0).map(x => new Tree());
this.divided = true;
return;
}
getContents(row, currentRow) {
if (currentRow === undefined) {
currentRow = 0;
}
if (row === currentRow) {
console.log('Contents:', this.contents)
return this.contents;
}
if (this.divided) {
console.log(row, currentRow)
currentRow++;
this.children[0].getContents(row, currentRow);
} else {
return;
}
}
}
答案 0 :(得分:2)
您看到的console.log
是此次通话的结果:
if (this.divided) {
console.log(row, currentRow)
currentRow++;
this.children[0].getContents(row, currentRow); //<-- here
// this is calling getContents() but ignores the return value
但是在这种情况下你实际上并没有返回任何内容,因此内部console.log()
会触发,但返回值是未定义的。
我不确定代码应该做什么,但是当满足条件时返回一个值会导致整个函数的返回值:
if (this.divided) {
console.log(row, currentRow)
currentRow++;
return this.children[0].getContents(row, currentRow);
答案 1 :(得分:0)
它将1记录到控制台,因为您调用了
results
当前行未定义,因为您未在参数
中传递它tree.pour(10)
所以它意味着currentRow为0而row(1)不等于currentRow(0),这就是它返回undefined的原因。
if (currentRow === undefined) {
currentRow = 0;
}
if (row === currentRow) {
console.log('Contents:->', this.contents)
return this.contents;
}