javascript - 无论返回语句是否足够,递归函数都返回未定义
问题描述
我已经阅读了一些关于它的问题和答案。看起来我的递归函数有足够的“返回”语句,所以......我不知道为什么它返回未定义......我添加了额外的日志语句以表明函数本身找到了元素,但没有返回它...
let animals = [
{
name: "dogs",
id: 1,
children: [
{
name: "lessie",
id: 2
},
{
name: "bark-a-lot",
id: 3
}
]
},
{
name: "cats",
id: 4,
children: [
{
name: "meows-a-lot",
id: 5,
children: [
{
name: "meows-a-lot-in-the-morning",
id: 6
}
]
},
{
name: "whisk-ass",
id: 7
}
]
}
];
function recurseFind(node, id) {
if (Array.isArray(node)) {
return node.forEach(el => {
return recurseFind(el, id);
});
} else {
if (node.id === id) {
console.log("node matched", node.id, id, node);
return node;
} else if (node.children) {
return node.children.forEach(child => {
return recurseFind(child, id);
});
} else {
return "not found";
}
}
}
const found = recurseFind(animals, 6);
console.log("found", found, "wtf");
解决方案
forEach
返回undefined
,所以
return node.forEach(el => {
return recurseFind(el, id);
});
undefined
无论递归调用找到什么,都会返回。
我会改用for
循环,如果找到匹配项,则返回它:
let animals = [
{
name: "dogs",
id: 1,
children: [
{
name: "lessie",
id: 2
},
{
name: "bark-a-lot",
id: 3
}
]
},
{
name: "cats",
id: 4,
children: [
{
name: "meows-a-lot",
id: 5,
children: [
{
name: "meows-a-lot-in-the-morning",
id: 6
}
]
},
{
name: "whisk-ass",
id: 7
}
]
}
];
function recurseFind(node, id) {
if (Array.isArray(node)) {
for (const el of node) {
const result = recurseFind(el, id);
if (result) return result;
}
} else {
if (node.id === id) {
return node;
} else if (node.children) {
for (const child of node.children) {
const result = recurseFind(child, id);
if (result) return result;
}
}
}
}
const found = recurseFind(animals, 6) || 'not found';
console.log("found", found);
推荐阅读
- c# - 统一二维。查找沿轴移动的对象的坐标
- python - 从列表列表中删除停用词
- python - 如何使用nodejs验证密码?
- php - Laravel 将翻译文件的内容作为数组获取
- python - 为什么我的 plt.plot() 在绘制弹丸运动时不起作用?
- amazon-web-services - AWS - Cognito 联合身份
- python-3.x - Tensorboard(超级初学者) - 需要简单的历元损失图,InvalidArgumentError 上的错误:int64 的 attr 'T' 的值不在列表中
- c++ - 为什么析构函数调用比构造函数调用多
- gitlab - GitLab CI/CD - 同时使用包括:和需求:
- javascript - 比较 Chai 中的错误数组