// 数据结构
var data= {
"text" : "1",
"children" : [{
"text" : "11",
"children" : [{
"text" : "111",
"children" : []
},{
"text" : "112",
"children" : []
}]
},{
"text" : "12",
"children" : []
}]
};
//num记录节点的所有叶子节点个数
function sumNode(data) {
if(data.children && data.children.length > 0){
var leafCount = 0
for (var i = 0; i < data.children.length; i++) {
leafCount = leafCount + sumNode(data.children[i])
}
data.num= leafCount
return leafCount
} else {
data.num= 1
return 1
}
}
sumNode(data);
关键:
else是一级结点完整结束的标志,是数值累加的基础
else{
data.num= 1;
return 1;
}