2010-11-05 138 views
0

需要更多的帮助,我想我有递归工作正常,但我无法得到原始请求项目的属性设置为正确的值。用递归函数和返回值

这里的目标是找到嵌套项目(基于Dictionary“parent”属性的分类法)的最顶层父项(或“ancestor”,depth = 0),并分配最初请求的嵌套项目的“ancestor”属性因此。

例如,在

苹果
- 红
- - 帝国
- - - “苹果” 新鲜

“新鲜” 的始祖应该设置为

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

REQUEST

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

最后,这里是基于我的许多调试语句的跟踪输出的一个片段:

治疗的父(吃障碍)不是根。循环。
饮食失调的母公司(身心)不是根。循环。
心身的父(疾病/疾病)是不是根。循环。
疾病/疾病的父(个人)不是根。循环。
个人的父(健康)是不是根。循环。
健康的父母是根(人)。 DONE。
定型处理的祖先为[默认]

正如你所看到的,而递归确实找到根,最初请求的项目仍然得到默认值。我错过了什么?

回答

0

我猜在else语句你想:

ancestor = getAncestor(taxonomy[obj]); 

现在你调用递归,但什么都不做有返回值,所以你永远不会更新祖先变量。

同样,breakreturn后声明是毫无意义。 :)

如果我理解正确的事情,你也许真的能够做到:

return getAncestor(taxonomy[obj]); 

否则你的循环将继续运行。如果没有,你的循环会遍历分类中的所有东西,即使它看到的第一个循环是递归的。

+0

这样做。这次我差点拿到了。感谢您的简单修复! – atwixtor 2010-11-05 19:14:54

0

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

+0

如果它不是一个Dictionary对象,我会的。在动作中,术语对象都处于同一级别,每个术语都有一个“父”属性,并带有父项术语ID的值。 – atwixtor 2010-11-05 19:17:13

+0

啊,我跳过了说Dictionary的地方。 :) – Robusto 2010-11-05 19:18:34