<html>
<head>
    <title>递归算法</title>
</head>
<script type="text/javascript">
var arr=  [{
           id: '10',
            label: '菜单10',
            children: [{
                  id:'1010',
                  label: '菜单1010',
                  children:[{
                      id:'101010',
                      label: '菜单101010',
                      children:[{
                          id:'10101010',
                          label: '菜单10101010',
                          children:[]
                      }]
                  }]
            }]
        },{
             id: '11',
              label: '菜单11',
              children: [{
                  id:'1110',
                  label: '菜单1110',
                  children:[{
                      id:'111010',
                      label: '菜单111010',
                      children:[{
                          id:'11101010',
                          label: '菜单11101010',
                          children:[]
                      }]
                  }]
              }]
        }]


//获取指定id的子节点id数组

function getChildIds(arr,id){
    var childIds=[]
     function a(arr){
         for(var i=0;i<arr.length;i++){
               if(id.length >=arr[i].id.length){
                    //console.log(id,arr[i].id,id.startsWith(arr[i].id))
                    if(id.startsWith(arr[i].id)){
                         if(arr[i].id.length ==id.length){
                              childIds.push(arr[i].id)
                         }
                         a(arr[i].children)
                    }
               }else{
                    if(arr[i].id.startsWith(id)){
                         childIds.push(arr[i].id)
                         a(arr[i].children)
                    }
               }
         }
     }
     a(arr)
     return childIds
}

var childIds= getChildIds(arr,'11')

console.log('childIds>>>>',childIds)

</script>
<body>


</body>
</html>
posted on 2018-06-30 22:36  高尔础础  阅读(595)  评论(1编辑  收藏  举报