TypeScript递归函数返回undefined

时间:2018-06-03 12:43:57

标签: typescript recursion tree

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

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

我编写了一个函数来查找给定Ref:

的类别节点
let x = this.navigateToNode(this.activeCategories[0], 2);

当我调用

时,此函数返回null
return value;

我可以看到它命中 <template v-for = "background in backgrounds" > <template v-if="currentBackground.path === background.path"> <div class="m-1 background inline-block rounded-circle" style="width: 100px; height: 100px; overflow: hidden"> <img class="img-fluid " :src="background.path" v-on:click="changeBack(background)" :style="circledPositionStyle" v-on:load="inquadraThumb(background)"> </div> </template> </template> ,因此找到了正确的节点,但是返回undefined。

1 个答案:

答案 0 :(得分: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.
}