简体   繁体   中英

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. 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. 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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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