【问题标题】:More help needed with recursive function and returned value递归函数和返回值需要更多帮助
【发布时间】:2011-05-05 18:45:39
【问题描述】:

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

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

例如,在

苹果
- 红色
- - 帝国
- - - 新鲜

“Fresh”的祖先应该设置为“Apples”。

虽然我在“按需”和个人基础上尝试此操作,但我愿意接受一种解决方案,即一次性标记与同一祖先相关的所有孩子或声明,因为这可能会更有效率。

请求

for (var mc:Object in taxonomy) {
        var term = taxonomy[mc];
        term["ancestor"] = getAncestor(term);
        trace("Setting " + term.name + "'s ancestor as [" + term.ancestor + "]");
        ... }

功能

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

最后,这是基于我的许多调试语句的跟踪输出的 sn-p:

治疗的父母(饮食失调)不是根。循环播放。
饮食失调的父母(心身)不是根。循环播放。
心身的父母(疾病/疾病)不是根。循环播放。
疾病/疾病的父母(个人)不是根。循环播放。
个人的父母(健康)不是根。循环播放。
健康的父母是根(人)。完成。
将治疗的祖先设置为 [默认]

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

【问题讨论】:

    标签: actionscript loops recursion


    【解决方案1】:

    我猜你想要的 else 语句:

    ancestor = getAncestor(taxonomy[obj]);
    

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

    此外,return 语句之后的 break 是毫无意义的。 :)

    如果我理解正确,您实际上可以这样做:

    return getAncestor(taxonomy[obj]);
    

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

    【讨论】:

    • 就可以了。这次我几乎吃到了。感谢您轻松修复!
    【解决方案2】:

    也许我错过了一些东西,但我不明白你为什么需要使用递归来做到这一点。在普通函数中,只需遍历目标的父对象,直到找到根对象,然后将 Fresh 的祖先设置为该对象。

    【讨论】:

    • 如果它不是 Dictionary 对象,我会的。在 actionscript 中,term 对象都处于同一级别,每个 term 都有一个“parent”属性,其值为 parent 的 term ID。
    • 啊,我跳过了它说字典的部分。 :)
    猜你喜欢
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2021-12-26
    • 2020-09-08
    • 1970-01-01
    相关资源
    最近更新 更多