使用zTree来显示文件树, 数据格式类似于:
1 var data = { 2 id: 1, 3 children: [ 4 { 5 id: 2, 6 children: [ 7 { 8 id: 3, 9 children: [ 10 { 11 id: 8, 12 children: [] 13 }, 14 ] 15 }, 16 { 17 id: 5, 18 children: [] 19 } 20 ] 21 }, 22 { 23 id: 4, 24 }, 25 { 26 id: 6, 27 children: [] 28 }, 29 { 30 id: 7, 31 children: [] 32 } 33 ], 34 }
一则小问题, 如何计算节点总数.
当然是递归了那么, 思路就是 total = 1 + iter(children), 1代表节点本身.
核心代码3行就够了.
1 function counter(data) { 2 // total = self + count(children); 3 if (typeof data.children === "undefined") { 4 return 1; 5 } 6 return 1 + data.children.reduce(function (prev, item) { 7 return prev + counter(item); 8 }, 0); 9 }