js递归

所谓的递归就是程序自己调用自己,下面就是一个最简单的递归。

function digui(value) {
    console.log('top不走');
    if (!value) {
        console.log('我走了')
    } else {
        digui(--value);  // 递归调用
    }
    console.log('bottom不走');
}

console.log('开始');
digui(2)

一个树的递归→把json树变成数组,如下是json树

{
	"retCode": "200",
	"message": "成功。",
	"data": {
		"name": "全公司",
		"id": "1",
		"children": [{
			"name": "惠商",
			"id": "1005666318466158594",
			"children": [],
			"parentId": "1"
		}, {
			"name": "百应平台",
			"id": "1005666472258703",
			"children": [],
			"parentId": "1"
		}, {
			"name": "小微租赁",
			"id": "1005666521109762",
			"children": [],
			"parentId": "1"
		}, {
			"name": "联想移动",
			"id": "1008898982221549569",
			"children": [],
			"parentId": "1"
		}, {
			"name": "QQ测试用",
			"id": "1013268991818338305",
			"children": [{
				"name": "QQtest",
				"id": "1013285036314595330",
				"children": [],
				"parentId": "1013268991818338305"
			}, {
				"name": "QQ test01",
				"id": "1013292514666352642",
				"children": [{
					"name": "QQ test01",
					"id": "1013292514666352682",
					"children": [],
					"parentId": "1013292514666352642"
				}],
				"parentId": "1013268991818338305"
			}],
			"parentId": "1"
		}],
		"parentId": "0"
	}
}

实现方式:

methods:{      //vue方法为例
    // 把树转成数组
    treeduigui(node){      
      arrtree=[]
        for(var i=0;i 0) {
                this.treeduigui2(node[i])
            }                        
        }       
       this.arrtree=arrtree
      //  console.log(this.arrtree)
    },
    treeduigui2(node){        
            if (node.children.length > 0) {                  
                for (var j = 0; j < node.children.length; j++) {    
                     var item1 = node.children[j];  
                     this.treeduigui2(item1);                
                    var obj1={
                        id:item1.id,
                        postName:item1.name
                    }    
                  arrtree.push(obj1)                                             
                }                   
            } 
           this.arrtree=arrtree    
          //  console.log(this.arrtree)                                 
    },
    loaddata(){
        this.treedigui(this.treeData)//假设this.treeData就是上面从后端接受的的json数据中的data
    }
},
mounted: function() {
    this.loaddata()
}

 

你可能感兴趣的:(javascript)