无论是否有足够的 return 语句,递归函数都返回 undefined [英] Recursive function returns undefined regardless of enough return statements
本文介绍了无论是否有足够的 return 语句,递归函数都返回 undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经阅读了一些关于它的问题和答案.看起来我的递归函数有足够的返回"语句,所以......我不知道为什么它返回 undefined......我添加了额外的日志语句来表明函数本身找到了元素,但没有返回它...
I have read a few questions and answers on it already. It looks like my recursive function has got enough "return" statements, so... I do not know why it returns undefined... I have added extra log statement to show that the function itself finds the element, but does not return it...
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
,无论递归调用找到什么.
will always return undefined
, no matter what the recursive calls find.
我会改用 for
循环,如果找到匹配项,则返回它:
I'd use a for
loop instead, and if a match is found, return it:
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);
这篇关于无论是否有足够的 return 语句,递归函数都返回 undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文