javascript 递归的几种用法

1. 从数组中递归查找符合条件的一个对象

function filterRoleBtn(path, arr) {
    for (const item of arr) {
      if (item.path == path) return item
      if (item.subMenu && item.subMenu.length>0) {
        const _item = filterRoleBtn(path, item.subMenu)
        if (_item) return _item
      }
    }
}

2. 从数组中递归查找符合条件的多个对象,并返回一个数组

// 查找当前路由下的需要显示的按钮
export function filterShowBtn(type,arr) {
    var o = []; //专门用来保存筛选后的数组
    arr.forEach(function(item) {
        if (item.type = type) {
            o.push(item)
        } else if (item.subMenu && item.subMenu.length > 0) {
            let _item = getID(type, item.subMenu)//递归
            o.push(_item)
        }
    });
    return o; //全部遍历完之后返回数组o
}

猜你喜欢

转载自blog.csdn.net/weixin_48309048/article/details/128210236