2017-02-23 36 views
0

我想知道如何得到节点的后代数。D3.js树的布局 - 想要得到的子孙数

我可以得到使用此代码的儿童人数。

console.log(d.children.length); 

但是我怎样才能得到该节点的后裔数呢?

我需要使用循环吗?

任何帮助将不胜感激。

回答

1

这是递归。

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));

+0

感谢,但没有工作 – Guru

+0

什么不正常?你怎么使用它? –

+0

如果您的孩子有孩子,则不计算父母。如果A有孩子B,C和B有D,E,那么A的后代数应该是4,但你的应该输出3,(C,D,E) – Guru