1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script> 9 var treeNodes = [ 10 { 11 id: "1", 12 name: ‘name1‘, 13 children: [ 14 { 15 id: "1-1", 16 name: ‘name1-1‘, 17 children: [ 18 { 19 id: "1-1-1", 20 name: ‘name1-1-1‘, 21 children:[] 22 }, 23 { 24 id: "1-1-2", 25 name: ‘name1-1-2‘ 26 } 27 ] 28 }, 29 { 30 id: "1-2", 31 name: ‘name1-2‘, 32 children: [] 33 } 34 ], 35 users: [] 36 }, 37 { 38 id: "2", 39 name: ‘name2‘, 40 children: [ 41 { 42 id: "2-2", 43 name: ‘name2-1‘, 44 children: [] 45 } 46 ] 47 } 48 ]; 49 50 //递归实现 51 var parseTreeJson = function(treeNodes){ 52 if (!treeNodes || !treeNodes.length) return; 53 54 for (var i = 0, len = treeNodes.length; i < len; i++) { 55 56 var childs = treeNodes[i].children; 57 58 console.log(treeNodes[i].id+‘ID‘); 59 60 if(childs && childs.length > 0){ 61 parseTreeJson(childs); 62 } 63 } 64 }; 65 66 console.log(‘------------- 递归实现 ------------------‘); 67 parseTreeJson(treeNodes); 68 69 </script> 70 </body> 71 </html>
此方法对二叉树提供的数据有要求,第一层循环遍历时,treeNodes,而后每深入一层,用的都是childs,比方说第二层就是children.children,第三层也是如此,这就要求提供的数据必须按照一定的格式;
时间: 2024-11-06 05:21:34