简体   繁体   English

用递归中断循环

[英]break for of loop with recursion

I have a function that takes a node and an object. 我有一个需要一个节点和一个对象的函数。 The larger object potentially has property of children and that is an array of similar shaped nodes. 较大的对象可能具有children对象的属性,并且是一组相似形状的节点。 The function is looking at the top level, and then if there are children look through each of those until the matching node is found. 该功能在顶层,然后如果有子级,则逐一浏览直到找到匹配的节点。

My console.log statement always logs something. 我的console.log语句总是记录一些内容。 But the function keeps running. 但是该功能保持运行。 I belive it isn't breaking the loop of looking at the rest of the children. 我相信这并没有打破看着其余孩子的循环。

What am I missing to completely exit this function when a match is found? 找到匹配项后,我想完全退出此功能的什么原因?

findNodeInStateHierarchy = (node, stateHierarchyNode) => {
    if (node.id === stateHierarchyNode.id) {
      console.log(stateHierarchyNode);
      return stateHierarchyNode;
    }
    else {
      if (stateHierarchyNode.children) {
        for (let child of stateHierarchyNode.children) {
          this.findNodeInStateHierarchy(node, child);
        }
      }
   }
}
findNodeInStateHierarchy = (node, stateHierarchyNode) => {
    if (node.id === stateHierarchyNode.id) {
      console.log(stateHierarchyNode);
      return stateHierarchyNode;
    } else {
      if (stateHierarchyNode.children) {
        for (let child of stateHierarchyNode.children) {
          const result = this.findNodeInStateHierarchy(node, child);
          if (result !== null) {
              return result;
          }
        }
      }
      return null;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM