如何递归访问儿童的孩子?

时间:2010-03-10 11:46:47

标签: flex actionscript-3 actionscript

我有一个Canvas,里面有很多组件,那些组件里面有很多组件。

getChildren()仅返回顶级子级。检索所有孩子(孩子的孩子等等)的最佳方法是什么。

好吧,我知道如何通过遍历子节点来实现这一点,但代码非常混乱。我更喜欢使用一个很好的递归函数。有没有人写过这个?或者有一个Util类来做这个吗?

3 个答案:

答案 0 :(得分:3)

尝试一些可能的事情(请注意,如果要收集所有对顶级迭代的引用,可以递归返回列表)

function inspect(object:DisplayObject):void
{
    if(object is DisplayObjectContainer)
    {
        var casted:DisplayObjectContainer = object as DisplayObjectContainer

        trace("DisplayObjectContainer ", casted.name)

        for(var depth:int = 0; depth < casted.numChildren;depth++)
        {
            inspect(casted.getChildAt(depth))
        }

    }else{

        trace("DisplayObject", object.name );
    }
}


inspect(this)

答案 1 :(得分:3)

private function recuse(display : DisplayObjectContainer) : void {
  if(display) {
    for (var i : int = 0;i < _display.numChildren;i++) {
        var child : DisplayObject = display.getChildAt(i);
        trace(child.name);
        if(child is DisplayObjectContainer) {
            recuse(DisplayObjectContainer(child));
        }
    }
}

}

答案 2 :(得分:1)

function theCallbackFunction(obj:DisplayObject):void
{
  trace(obj.name);
}

//Visit the children first.
//Deep most objects will be visited first and so on.
//stage is visited at the end.
//Uses recursion
function depthFirst(obj:DisplayObject, func:Function):void
{
  if(!(obj instanceof DisplayObjectContainer))
  {
    func(obj);
    return;
  }
  var p:DisplayObjectContainer = DisplayObjectContainer(obj);
  var len:Number = p.numChildren;
  for(var i:Number = 0; i < len; i++)
  {
    var child:DisplayObject = p.getChildAt(i);
    depthFirst(child, func);
  }
  func(obj);
}   

//Visit the siblings first.
//stage is visited first, then its children, then the grand children and so on
//No recursion.
function breadthFirst(obj:DisplayObject, func:Function):void
{
  var q:Array = []; 
  q.push(obj);
  var p:DisplayObjectContainer;
  var i:Number, len:Number;
  while(q.length != 0) 
  {     
    var child:DisplayObject = queue.shift();
    func(child);
    if(!(child instanceof DisplayObjectContainer))
      continue;         
    p = DisplayObjectContainer(child);
    len = p.numChildren;
    for(i = 0; i < len; i++) 
      q.push(p.getChildAt(i));
  }     
}

depthFirst(this.stage, theCallbackFunction);
breadthFirst(this.stage, theCallbackFunction);