How to access children of children recursively?

帅比萌擦擦* 提交于 2019-12-24 18:35:14

问题


I have a Canvas which has many components inside it and those again, have many components inside them.

getChildren() returns only the top level children. What is the best way to retrieve all the children (children of children of children and so on).

Well, I sorta know how to do this by iterating through the children, but the code is really messy. I'd prefer to use a nice recursive function. Has anyone written this before? Or is there a Util class to do this?


回答1:


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:


Try something likely (note you can return the lists recursively if you want to gather all the references to the top level iteration)

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)



回答3:


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


来源:https://stackoverflow.com/questions/2416553/how-to-access-children-of-children-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!