js遍历树,递归方法优化多层嵌套for循环
1.需求
通过菜单权限来显示相应的内容
菜单形式:一级菜单+二级菜单+三级菜单
permission_routers:[
{
path: "/purchase1"
name: "purchaseManagement"
meta: Object
children: [
path: "/purchase/balance"
name: "purchaseBalanceManagement"
meta: Object
children: [
path: "pre-contract-list"
name: "purchasePreContractList"
meta: Object
]
]
}
{
path: "/purchase2"
name: "purchaseManagement"
meta: Object
children: [
path: "/purchase/balance"
name: "purchaseBalanceManagement"
meta: Object
children: [
path: "pre-contract-list"
name: "purchasePreContractList"
meta: Object
]
]
}
]
2.分析
方式一:
1.把所有菜单(一级菜单+二级菜单+三级菜单)全部遍历出来push到一个空数组中
2.先循环遍历一级菜单,把所有以及菜单的name放到空数组中,同时遍历每个一级菜单是否有子菜单,有的话,继续遍历子菜单,把子菜单的name放到数组中,同时遍历每个二级菜单,看是否有子菜单,有的话,遍历子菜单,把子菜单的name放到数组中
getUserRolesPermissions(){
let arr = []
this.permission_routers.forEach(item => {
const itemObj = this.MixinClone(item)
delete itemObj.children
arr.push(itemObj)
if (item.children) {
item.children.forEach(jtem => {
const jtemObj = this.MixinClone(jtem)
delete jtemObj.children
arr.push(jtemObj)
if (jtem.children) {
jtem.children.forEach(ktem => {
const ktemObj = this.MixinClone(ktem)
delete ktemObj.children
arr.push(ktemObj)
})
}
})
}
})
this.menuFeatures = arr
},
方式二(使用递归):
getUserRolesPermissions(permission_routers,menuFeatures){
permission_routers.forEach(item => {
const itemObj = this.MixinClone(item)
delete itemObj.children
menuFeatures.push(itemObj)
if(item.children){
this.getUserRolesPermissions(item.children,menuFeatures)
}
})
},
3.总结
1.使用普通的办法:
上面的源代码只有三级,就已经很长了,而且每多一级就要多想一个变量名,如果层级更多,那光想变量名就头疼了,从可读性与维护性来说都不适合,所以要用递归来实现。
3.递归遍历树数据
递归,就是在运行的过程中调用自己,大大减少了代码量
窘迫的日子里,却总是有它好玩的地方