zoukankan      html  css  js  c++  java
  • 【转载】AS3.0中遍历删除容器内子对象的误区

    为什么会索引超出范围呢?再次分析下代码。发现num确实是固定不变了,但是a.removeChildAt(i);却出现了问题
    由于as3新的的深度管理机制,当执行第一次循环后,深度为零的对象被删除,深度为1--5的对象的深度会自动减一。
    因此深度为0的位置依然有对象存在。当三次循环后a.numChidlren变成3、i变成3。执行第四循环的时候会报错,因为
    已经找不到索引为3位置的对象了。为了验证这种想法执行下面代码

    <!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->a1.name="a1";
    a2.name="a2";
    a3.name="a3";
    a4.name="a4";
    a5.name="a5";
    a6.name="a6";
    var num=a.numChildren;
    try{
        for(var i:uint=0;i<num;i++){
            a.removeChildAt(i);
        }
    }catch(e){}
    for(var j:uint=0;j<a.numChildren;j++){
        trace(a.getChildAt(j).name)
    }

           分别给a里面每个子对象添加name属性,然后在执行遍历删除后,输出a里面还存在的对象的name。发现输出结果是a2、a4、a6。

    这说明在遍历删除之前深度为奇数的对象被删除了,(为什么只有深度为奇数的对象被删除了,根据as3的深度管理机制揣摩下就能明白了)
      既然as3有这样的深度管理机制,那么不管怎么删除,深度为0位置的始终有对象存在。把代码改成

    <!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->var num=a.numChildren;
    for(var i:uint=0;i<num;i++){
        a.removeChildAt(0);
    }
    trace(a.numChildren);

           就可以了,可以发现trace的结果是0,说明a里面的子对象全部被删除了。

    注意:千万不要把for(var i:uint=0;i<num;i++)换成for(var i:uint=0;i<a.numChildren;i++),想想为什么?(原理跟上面的一样)
      如果觉得这样写麻烦的话,还可以用下面的写法

    <!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->while(a.numChildren>0){
        a.removeChildAt(0);
    }

    实际上我是在看到用while来遍历删除的方法后,才发现我以前用for来遍历删除的问题的,建议大家用最最后一种写法,这样写的代码最简单。

  • 相关阅读:
    颜色混合openglglBlendFunc函数
    Types of Maps
    ogre 检测显卡gpu支持参数
    (转载)lua和c/c++互相调用实例分析
    光照模型
    阴影(转载)
    eval()解析JSON
    android中The connection to adb is down,问题和解决 AndroidEclipseAntXML
    比较android中的像素单位dp、px、pt、sp
    区别:DOM Core 与 HTMLDOM
  • 原文地址:https://www.cnblogs.com/sumsung753/p/3821500.html
Copyright © 2011-2022 走看看