我编写了一个函数来检查我的树是否包含值。每个树/子树都有一个我的函数遍历的子数组。为什么我不能使用forEach来遍历树的孩子?
function Tree (value) {
this.value = value;
this.children = [];
}
Tree.prototype.addChild = function (node) {
this.children.push(node);
return true;
};
Tree.prototype.contains = function (value) {
if (this.value === value) return true;
this.children.forEach(el => {
return el.contains(value);
});
return false;
};
let myTree = new Tree(2);
let firstLevelChild = new Tree(7);
let secondLevelChild = new Tree(3);
myTree.addChild(firstLevelChild);
firstLevelChild.addChild(secondLevelChild);
console.log(JSON.stringify(myTree, null, 2));
console.log('2: ',myTree.contains(2))
console.log('7: ',myTree.contains(7))
console.log('3: ',myTree.contains(3))

答案 0 :(得分:2)
因为forEach
并不关心其回调的返回值。它保持循环,无论如何,并且它本身没有(有意义的)返回值。
您希望some
并返回其结果:
Tree.prototype.contains = function (value) {
if (this.value === value) return true;
return this.children.some(el => {
return el.contains(value);
});
};
甚至更紧凑(如果这是一个目标):
Tree.prototype.contains = function (value) {
return this.value === value || this.children.some(el => el.contains(value));
};
直播示例:
function Tree (value) {
this.value = value;
this.children = [];
}
Tree.prototype.addChild = function (node) {
this.children.push(node);
return true;
};
Tree.prototype.contains = function (value) {
return this.value === value || this.children.some(el => {
return el.contains(value);
});
};
let myTree = new Tree(2);
let firstLevelChild = new Tree(7);
let secondLevelChild = new Tree(3);
myTree.addChild(firstLevelChild);
firstLevelChild.addChild(secondLevelChild);
console.log('2: ',myTree.contains(2));
console.log('7: ',myTree.contains(7));
console.log('3: ',myTree.contains(3));

some
调用其回调,直到回调返回truthy值,然后停止。如果回调值返回真值,some
将返回true
;如果没有,some
会返回false
。