Javascript 陷入递归返回值中
我编写了一个小的递归函数来查找menuItem的级别。 以下是函数:Javascript 陷入递归返回值中,javascript,recursion,Javascript,Recursion,我编写了一个小的递归函数来查找menuItem的级别。 以下是函数: const getSelectedMenuItemLevel = (menuItems, path, level = 0) => menuItems.forEach((menuItem) => { console.log(menuItem.path, path, menuItem.path === path, level); if (menuItem.path === path) { return
const getSelectedMenuItemLevel = (menuItems, path, level = 0) => menuItems.forEach((menuItem) => {
console.log(menuItem.path, path, menuItem.path === path, level);
if (menuItem.path === path) {
return level;
}
return getSelectedMenuItemLevel(menuItem.children, path, level + 1);
});
我这样称呼它:
console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));
以下是menuItems阵列:
[
{
path: 'one',
name: 'One',
children: [
{ path: 'one/one', name: 'One/One', children: [] },
{ path: 'one/two', name: 'One/Two', children: [] },
],
},
{
path: 'two',
name: 'Two',
children: [
{ path: 'two/one', name: 'Two/One', children: [] },
{ path: 'two/two', name: 'Two/Two', children: [] },
{ path: 'two/three', name: 'Two/Three', children: [] },
],
},
{
path: 'three',
name: 'Three',
children: [],
}
]
这个递归函数总是返回我
未定义的。我希望它返回level
您需要函数中的一个变量,并通过检查迭代找到的级别来存储它,因为如果找到有效级别,此方法将使用短路
基本上,您需要将想要的返回值扩展为undefined
或一个数值
const getSelectedMenuItemLevel=(菜单项,路径,级别=0)=>{
让价值;
menuItems.some((menuItem)=>{
if(menuItem.path==路径){
价值=水平;
返回true;
}
const temp=getSelectedMenuItemLevel(menuItem.children,路径,级别+1);
如果(临时){
数值=温度;
返回true;
}
返回false;
});
返回值;
};
变量菜单项=[
{
路径:“一”,
名称:“一”,
儿童:[
{路径:'one/one',名称:'one/one',子项:[]},
{路径:'one/two',名称:'one/two',子项:[]},
],
},
{
路径:“二”,
姓名:"两",,
儿童:[
{路径:'two/one',名称:'two/one',子项:[]},
{路径:'two/two',名称:'two/two',子项:[]},
{路径:'two/three',名称:'two/three',子项:[]},
],
},
{
路径:"三",,
姓名:"三",,
儿童:[],
}
];
log(getSelectedMenuItemLevel(menuItems,'two/three')代码>总是返回未定义的值,您不能从中返回任何其他值。@RobG那么我应该使用什么来代替它呢<代码>映射
?可能,但过滤器也可能工作。@RobG我会试试。我认为filter
不起作用,因为filter将返回一个项,而不是返回值
。我试过了。它工作正常,除了警告。在some
的末尾应该有returnfalse
。我将编辑您的答案并添加它以供将来参考。非常感谢您花时间解决此问题。默认情况下,该函数返回undefined
,如果some
将其解释为错误值,则返回该值。