在JavaScript中完成第一个递归分支后返回树

时间:2020-03-04 13:59:23

标签: javascript recursion

我在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]);

我的问题是,一旦到了叶子,我如何检查兄弟姐妹或父分支,直到整个树都被解析了?

1 个答案:

答案 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