2017-02-23 37 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