首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用递归函数和返回值需要更多帮助

使用递归函数和返回值需要更多帮助
EN

Stack Overflow用户
提问于 2010-11-05 19:01:15
回答 2查看 306关注 0票数 0

我认为递归正常工作,但我无法将最初请求的项的属性设置为正确的值。

这里的目标是找到嵌套项的最顶层父项(或“祖先”,深度= 0) (基于字典“父”属性的分类法),并相应地分配最初请求的嵌套项的“祖先”属性。

例如,在

苹果

  • Red
    • Empire

      • Fresh

“新鲜”的祖先应该设置为“苹果”。

虽然我试图在“按需”和个人的基础上,我是开放的解决方案,标记所有与同一祖先相关的孩子在一次猛扑或声明,因为这可能会更有效。

请求

代码语言:javascript
复制
for (var mc:Object in taxonomy) {
        var term = taxonomy[mc];
        term["ancestor"] = getAncestor(term);
        trace("Setting " + term.name + "'s ancestor as [" + term.ancestor + "]");
        ... }

函数

代码语言:javascript
复制
function getAncestor(term:Object):String {

    var ancestor = "default";

    for(var obj:Object in taxonomy) {
        if(term.parent == taxonomy[obj].tid) { // If next object is current object's parent
            if(taxonomy[obj].depth == 0) { // And if object's parent is a root object
                // Then object's parent is the ancestor
                trace(term.name + "'s parent IS the root (" + taxonomy[obj].name + "). DONE."); // "term" here is NOT originally requested term
                return(taxonomy[obj].name); // Return DIRECTLY to function call and assign originally requested term with this name.
                break; // Get the hell out of here
            }
            else { // If object's parent is not a root object
                trace(term.name + "'s parent (" + taxonomy[obj].name + ") is NOT a root. LOOPING.");
                getAncestor(taxonomy[obj]); // Step function again with current object's parent object as current object
            }
        }
    }
    return(ancestor);
}

最后,下面是基于我的许多调试语句的跟踪输出片段:

治疗的父母(饮食障碍)不是根。绕圈。

饮食障碍的父母(心身)不是根源。绕圈。

心身父母(疾病/疾病)不是根源。绕圈。

疾病/疾病的父母(个人)不是根源。绕圈。

个人的父母(健康)不是根。绕圈。

健康的父母是根源(人)。完成了。

将处理的祖先设置为默认

正如您所看到的,虽然递归确实找到了根,但最初请求的项仍然获得默认值。我遗漏了什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-11-05 19:07:56

我猜在你想要的那句话里:

代码语言:javascript
复制
ancestor = getAncestor(taxonomy[obj]);

现在,您正在调用递归,但对返回值不做任何操作,因此永远不会更新祖先变量。

而且,在break语句之后的return也是毫无意义的。:)

如果我对事情的理解是正确的,你可能真的能做到:

代码语言:javascript
复制
return getAncestor(taxonomy[obj]);

否则,您的循环将继续运行。没有这一点,您的循环将遍历分类法中的所有内容,即使它看到的第一个循环是它递归的那个。

票数 0
EN

Stack Overflow用户

发布于 2010-11-05 19:14:49

也许我遗漏了一些东西,但我不明白为什么您需要使用递归来完成这个任务。在正常函数中,只需遍历目标的父对象,直到找到根对象为止,然后设置ancestor的祖先。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4109163

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档