如何找到连锁店的最后一个孩子

时间:2019-04-27 13:18:41

标签: javascript angular recursion

如何查找代码中给出的该链的最后一个元素是数组(Symptomaster历史记录数组)。

我使用了递归。我将在代码中显示。

//example data in array
0: SymptomasterHistory {parentId: -1, currentId: 798, rootBool: true, hasChild: true}
1: SymptomasterHistory {parentId: -1, currentId: 235, rootBool: true, hasChild: true}
2: SymptomasterHistory {parentId: 798, currentId: 799, rootBool: false, hasChild: false}
3: SymptomasterHistory {parentId: 235, currentId: 237, rootBool: false, hasChild: true}
4: SymptomasterHistory {parentId: 237, currentId: 274, rootBool: false, hasChild: false}

// recursion
findResultByParentId(parentId: number) {
        for (let i = 0; i < this.childSymptomaster.length; i++) {
            if(this.childSymptomaster[i].parentId === parentId && this.childSymptomaster[i].hasChild){
                this.findResultByParentId(this.childSymptomaster[i].currentId);
            }else{
                let id = this.childSymptomaster[i].currentId;
                this.childSymptomaster.splice(i,1);
                return id;
            }
        }
    }

使用递归的示例,其父ID为798,结果应为799。请帮助我。

1 个答案:

答案 0 :(得分:0)

它对您不起作用的原因是因为您在循环内具有递归大小写。实际上,您应该这样做:

function findResultByParentId(id) {
        // Find the current element
        var currentElement = this.childSymptomaster.find(function(e) { 
          return e.currentId === id;
        });
        // If current element id doesn't exist
        if (!currentElement) {
          // Return error value -1, null, undefined or similar
          return -1;
        }

        if (currentElement.hasChild) {
          // Recursive case
          // The element have a child - find it...
          var child = this.childSymptomaster.find(function(c) {
            return c.parentId === id;
          });
          // check for that child
          return findResultByParentId(child.currentId);
        } else {
          // Base case - we are at the bottom leaf
          return currentElement.currentId;
        }
    }

有关使用箭头功能的压缩版本:

function findResultByParentId(id) {
        // Find the current element
        let currentElement = this.childSymptomaster.find((e) => e.currentId === id);
        // If current element id doesn't exist
        if (!currentElement) {
          // Return error value -1, null, undefined or similar
          return -1;
        }

        if (currentElement.hasChild) {
          // Recursive case
          // The element have a child - find it...
          let child = this.childSymptomaster.find((c) => c.parentId === id);
          // Check for that child
          return findResultByParentId(child.currentId);
        } else {
          // Base case - we are at the bottom leaf
          return currentElement.currentId;
        }
    }

对于正在工作的矮人,请参见:https://plnkr.co/edit/leSUKQCpt5xCnFvSR0ca?p=preview