假設我有一個能容納自身的其它實例的類:如何遞歸獲取嵌套對象中的所有子項的列表?
function Thing() {
this.subThings = [];
}
我添加n
subThings
頂端的事情:
var rootThing = new Thing();
rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());
rootThing.subThings.push(new Thing());
然後我添加n
subThings
的一些rootThing
的的subThings
:
rootThing.subThings[0].subThings.push(new Thing());
rootThing.subThings[0].subThings.push(new Thing());
rootThing.subThings[0].subThings.push(new Thing());
在th是點,結構是這樣的:
rootThing
|
+--subThing
| |
| +--subThing
| |
| +--subThing
| |
| +--subThing
|
+--subThing
|
+--subThing
所以,我怎麼可以得到所有的subThing
S的rootThing
列表和所有的他們subThing
S'
function getAllChildren(beginNode) {
var allChildren = [];
beginNode.subThings.forEach(function(childNode) {
allChildren.push(childNode);
// allChildren = allChildren.concat(childNode.subThings); // something along these lines
});
return allChildren;
}
console.log(getAllChildren(rootThing));
'console.dir(rootThing)':) –
'的console.log(JSON.stringify(rootThing,假的,'「)) ' – lxe
想象一下,只有一個級別,並實現了一個打印'事物'+它的後代的函數。然後發佈。如果你這樣做,我們會告訴你如何將這個函數改變爲在幾個按鍵中遞歸。 – zerkms