gpt4 book ai didi

javascript - 为什么我不能用forEach来遍历一棵树?

转载 作者:行者123 更新时间:2023-11-30 14:49:49 26 4
gpt4 key购买 nike

我编写了一个函数来检查我的树是否包含一个值。每棵树/子树都有我的函数遍历的子数组。为什么不能用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))

最佳答案

因为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 调用其回调,直到回调返回真值,然后停止。如果回调返回真值,some 返回 true;如果不是,some 返回 false

关于javascript - 为什么我不能用forEach来遍历一棵树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318519/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com