有关js中递归返回undefined的问题

444 阅读1分钟

有关js中递归返回undefined的问题

  • 在调用递归函数的时候,通过console.log()打印有值,但是在获取的时候去是undefined,原因是在递归函数内部没有对递归函数进行return,所以外层函数无法接受到返回值
  • 如果想要函数最后一次计算所得值,就需要在每次调用该函数的时候进行return,每一次return都是把最新的函数调用返回给外层的函数调用
  function pathToMenu(userMenus: IMenuType, currentPath) {
    for(const menu of userMenus) {
      if(menu.type === 1) {
        // 此处在递归调用的时候没有return返回值,所以最后返回的值就是undefined
        pathToMenu(menu.children ?? [], currentPath)
      } else if(menu.type === 2 && menu.url === currentPath) {
        return menu
      }
    }
  }
  
  const menu = pathToMenu(userMenus, currentPath) // 此处的menu为undefined
  function pathToMenu(userMenus: IMenuType, currentPath) {
    for(const menu of userMenus) {
      if(menu.type === 1) {
        // 此处在递归调用的时候return返回值了,所以最后返回的值不为undefined
       const findMenu = pathToMenu(menu.children ?? [], currentPath)
       if(findMenu) {
         return findMenu
       }
      } else if(menu.type === 2 && menu.url === currentPath) {
        return menu
      }
    }
  }
  
  const menu = pathToMenu(userMenus, currentPath) // 此处的menu有值