卡在递归返回值中

时间:2018-10-26 08:09:45

标签: 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 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

1 个答案:

答案 0 :(得分:1)

您需要在函数中使用一个变量,并通过用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'));