美文网首页
for循环 递归,中断递归以及获取返回值

for循环 递归,中断递归以及获取返回值

作者: 我讲你思 | 来源:发表于2022-04-14 17:55 被阅读0次

    for循环 递归,中断递归以及获取返回值

    如下三级菜单,如果已知 path 为 /order/detail,现需要获取/order/detail所在菜单的层级,以及菜单名字和其他参数,若使用for循环,则至少需要三层循环才能找出,代码也不会太优雅,因此这里我使用了递归加for循环的办法,结果发现当找到目标时,循环并没有终止,返回值也是undefind,经过查找资料也是找到了相应的办法

    const menus =  [
        {
            id: 1,
            name: '菜单1',
            path: '/order/index',
            children: [
                {
                    id: 11,
                    name: '菜单11',
                    path: '/order/list',
                    children: [
                        {
                            id: 111,
                            name: '菜单111',
                            path: '/order/detail',
                            children: []
                        },
                        {
                            id: 111,
                            name: '菜单111',
                            path: '/order/refound',
                            children: []
                        }
                    ]
                }
            ]
        },
        {
            id: 2,
            name: '菜单2',
            path: '/produuct/index',
            children: [
                {
                    id: 22,
                    name: '菜单22',
                    path: '/product/list',
                    children: [
                        {
                            id: 222,
                            name: '菜单222',
                            path: '/product/detail',
                            children: []
                        },
                        {
                            id: 111,
                            name: '菜单111',
                            path: '/product/store',
                            children: []
                        }
                    ]
                }
            ]
        }
    ]
    
    const matchPath = (menus, path, level) => {
        for(let i =0; i< menus.length; i++) {
            const menuItem = menus[i]
            const menuPath =menuItem.path
            // 路由相等时返回
            if (menuPath === path) return {menuItem, level, isFind: true}; 
            // 如果已经找到,中断递归和返回数据
            if (menuItem.children && menuItem.children.length) {
                //再次递归时层级加1
                const targetMenu = matchPath(menuItem.children, path, level + 1)
                 //判断是否已经匹配到,匹配到中断循环和递归并返回
                if (targetMenu && targetMenu.isFind) return targetMenu;
            }
        }
    
    
    }
    
    matchPath(menus,'/order/detail' ,1)   
    
    返回数据如下:
     {
       menuItem:{
           id: 111,
           name: '菜单111',
           path: '/order/detail',
           children: []
        },
        level: 3,
        isFind: true
    }
    
    

    相关文章

      网友评论

          本文标题:for循环 递归,中断递归以及获取返回值

          本文链接:https://www.haomeiwen.com/subject/zftxertx.html