2010-08-31 52 views
2

我正在處理大量分層分類術語,其中每個術語(「203」)在舞臺上都有匹配的「term203」影片剪輯,並且無法獲得遞歸函數以返回所有一個給定的後代的後代。建立一箇舊的字典?字典遞歸幫助

有一個主Dictionary()對象與每個術語以下嵌套組織:

{ [object Movie Clip] : { "tid":203, "parent":99, "name":"Culture", selected:false, "otherData":"etc" } } 

...其中[object Movie Clip]的實例名稱將是"term203"。所有這些對象:subObjectArray項目(「術語」)都存儲在主對象taxonomy:Dictionary()中。

我一直試圖讓遞歸函數(這本身已經是一個小我頭上),需要一個影片剪輯的click.target並返回一個新Dictionary()對象與所有的孩子和孫子們和這個詞的孫子孫輩(等),在上面描述的同一個嵌套組織中。

下面的代碼會追蹤正確數量的遞歸循環,但返回的Dictionary()對象只包含第一次運行的條件(僅限所請求的術語的直接子代)。

var taxonomy:Dictionary = new Dictionary(); 

// ...Term info is loaded into taxonomy from a JSON-style text file) 
// ...MOUSE_OVER event listeners are added to each 

function revealChildren(hvr:MouseEvent):void { 

    trace("Spotlighting " + taxonomy[hvr.target].name + "'s children..."); 

    for(var key:Object in getAllChildren(taxonomy[hvr.target].tid)) { 
     trace("Animating " + taxonomy[key].tid); // Traces only immediate children 
     var revealTween = new Tween(key, "alpha", Regular.easeInOut, key.alpha, 1, 1, true); 
    } 
} 

function getAllChildren(origin):Dictionary { 

    var children:Dictionary = new Dictionary(); 

    for(var element:Object in taxonomy) { 
     if(taxonomy[element].parent == origin) { 
      var subSet = getAllChildren(taxonomy[element].tid); 
      children[element] = subSet; // *CAN'T ACCESS 'subSet' PROPERLY* 
      trace("Parent = " + origin); 
      trace("Matched! Adding " + taxonomy[element].tid + " as key and setting its value to " + subSet); // Traces correct amount of times, one for each descendent 
     } 
     else { 
     } 
    } 
    return children; 
} 

我當然不會聲稱是最有效的AS3程序員,所以我打開其他配置。但是,在嘗試使用靜態和嵌套數組之後,我寧願繼續使用Dictionary()對象作爲我的主池。

如前所述,只有直接子女最終在revealChildren()函數中進行動畫處理。這對我來說是神祕的,在輸出窗口中,所有後代都依次跟蹤(沒有特別的順序),在getAllChildren()函數中,

此外,我不能從subSet對象得到任何形式的名稱或財產。這可能是問題所在。

我只測試過它'兩代',但似乎只有第一輪調用函數成功地將這些條款添加到新的Dictionary()對象並將其完整返回給動畫功能。

太壞dict.filter(getDescendants)不起作用。請幫忙!

回答

2

爲了簡化,我添加了一個名爲children的輸出參數。這是我們的函數將存儲其結果的Dictionary。它有一個默認值,所以你不需要指定一個。在這種情況下,它會爲自己創建一個新的實例。

function getAllChildren(origin:*, children:Dictionary = null):Dictionary { 
    if (children = null) children = new Dictionary(); 

    for(var element:* in taxonomy) { 
     if(taxonomy[element].parent == origin) { 
      children[element] = taxonomy[element]; 
      getAllChildren(taxonomy[element].tid, children); 
     } 
    } 
    return children; 
} 

當一個孩子被發現,它準確地複製過來:children[element] = taxonomy[element];
接下來,函數遞歸調用自己,因爲已經使用它提供相同的輸出字典。


編輯:
針對您的評論...您的代碼最初稱這一發現一個名爲 element過了一會兒:

children[element] = getAllChildren(taxonomy[element].tid); 

你讓children[element]等於這裏Dictionary對象。您創建的是一個樹形結構,將MovieClip對象映射到Dictionary對象,其中包含其子對象的類似映射。在這個結構上使用for in循環只會給你頂層的孩子。它不會遞歸遍歷整個樹。

+0

工程就像一個魅力 - 非常感謝!我不知道我可以靈活地使用函數參數。 – atwixtor 2010-08-31 13:57:21

+0

爲了概念理解,有人可以解釋爲什麼原始遞歸不能按預期工作? – atwixtor 2010-08-31 22:13:47

+0

@atw:我在答案的末尾添加了一個解釋。 – Gunslinger47 2010-08-31 23:41:25