TypeScript递归函数返回undefined

问题描述 投票:1回答:1

我有一个具有以下结构的对象数组:

{
  Name: "Automotive"
  RefCategory: 1,
  ChildCategories:[{
     Name: "Car"
     RefCategory: 2,
     ChildCategories: []
  },{
     Name: "Motorcycle"
     RefCategory: 3,
     ChildCategories: []
  }]
}

我写了一个函数来找到一个类别节点,给出它的参考:

navigateToNode(node: any, RefCategoryToFind: number): any {

    if (node.RefCategory == RefCategoryToFind)
        return node;

    node.ChildCategories.forEach(value => {
        if (value.RefCategory == RefCategoryToFind)
            return value;
        else {
            if (value.ChildCategories.length !== 0)
                return this.navigateToNode(value, RefCategoryToFind);                
        }
    });
}

我调用时,此函数返回null

let x = this.navigateToNode(this.activeCategories[0], 2);

我可以看到它击中了return value;,从而找到了正确的节点,但返回undefined。

typescript recursion tree
1个回答
1
投票

你的回调函数返回一个值,但包装函数不会返回任何内容。尝试在找到返回值时保存并返回它:

navigateToNode(node: any, RefCategoryToFind: number): any {

    if (node.RefCategory == RefCategoryToFind)
        return node;

    var result;

    node.ChildCategories.forEach(value => {
        if (value.RefCategory == RefCategoryToFind) {
            result = value;
            return value;
        } else {
            if (value.ChildCategories.length !== 0)
                return this.navigateToNode(value, RefCategoryToFind);                
        }
    });
    return result.
}
© www.soinside.com 2019 - 2024. All rights reserved.