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