I'd like to know how could I get the count of descendant of node.
I can get the count of children using this code.
console.log(d.children.length);
But how can I get count of descendant of that node?
Do I need to use recurrence?
Any help would be appreciate.
This is with recursion.
function getCount(parent) { var count = 0; if (Array.isArray(parent.children)) { count += parent.children.length; parent.children.forEach(function(child) { if (Array.isArray(child.children)) { count += getCount(child); } }); } return count; } var d = { children: [ 1, { children: [ 1, 2 ] }, 2, 3 ] }; console.log(getCount(d));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.