gpt4 book ai didi

javascript - 陷入递归返回值

转载 作者:行者123 更新时间:2023-11-29 23:15:20 25 4
gpt4 key购买 nike

我写了一个小的递归函数来查找 menuItem 的级别。这是函数:

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: [],
}
]

这个递归函数总是返回undefined。我希望它返回 level

最佳答案

您需要函数中的一个变量,并通过使用 Array#some 检查找到的级别的迭代来存储它, 因为如果找到有效级别,此方法会使用短路。

基本上,您需要将所需的返回值扩展为 undefined 或数字值。

const getSelectedMenuItemLevel = (menuItems, path, level = 0) => {
let value;
menuItems.some((menuItem) => {
if (menuItem.path === path) {
value = level;
return true;
}
const temp = getSelectedMenuItemLevel(menuItem.children, path, level + 1);
if (temp) {
value = temp;
return true;
}
return false;
});
return value;
};


var 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: [],
}
];

console.log(getSelectedMenuItemLevel(menuItems, 'two/three'));

关于javascript - 陷入递归返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53004257/

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