【发布时间】: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