我在myObject
对象中具有以下形状的数据。我想在每个级别上使用performMyFunction()从downloads
数组中获取信息:
{
title (string)
downloads [{}]
contains [{
title (string)
downloads [{}]
contains [{
title (string)
downloads [{}]
contains [{}]
}]
}]
}
我编写了以下递归函数,该递归函数很适合在树上滑倒:
const recurseTree = (tree: any[]) => {
tree.forEach(a => {
a.downloads.forEach(b => {
this.performMyFunction(b.type);
});
recurseTree(a.contains);
});
};
recurseTree([myObject]);
我的问题是,一旦到了叶子,我如何检查兄弟姐妹或父分支,直到整个树都被解析了?
答案 0 :(得分:1)
您通常在此处执行的操作是将另一个参数传递给函数,该参数可能称为parent
。
例如
const recurseTree = (tree: any[], parent) => {
if (parent) {
//we have access to parent here..
}
tree.forEach(a => {
a.downloads.forEach(b => {
this.performMyFunction(b.type);
});
recurseTree(a.contains, tree); //let pass this tree as the parent
});
};
recurseTree([myObject], null); //we are the parent, lets pass null