如何通过在actionScript3中替换ArrayCollection中的旧值来添加新值?

时间:2012-08-21 06:50:30

标签: arrays actionscript-3 collections

  public var streamList:ArrayCollection=new ArrayCollection();
  //am getting the streamList dynamically like WebUser7,WebUser11.....      
  private function streamSynch(event:SyncEvent):void
    {
        if(streamList.length>0){
        //(streamList)here in streamList am getting the all values(old)
            streamList.removeAll();
        }
        var results:Object = event.target.data;
        for( var item:String in results ) {              
            streamArray.push(item);     
        }
        streams = new ArrayCollection(streamArray);
        streamList=streams; //(streamList)here in streamList am getting the all values(new) like Webuser9,WebUser2,WebUser11......
        From my Example i need to add the   Webuser9,WebUser2,WebUser11,WebUser7    
    }

我需要比较旧的和新的,然后替换旧的并添加新的...

1 个答案:

答案 0 :(得分:1)

您可以使用ArrayCollection方法setItemAt(item:Object, index:int):Object执行此操作。您只需要知道要替换的元素的索引。

修改

有用法示例

function arrayCollectionExample () : void {

    // create instance of array collection
    var arrayCollection : ArrayCollection = new ArrayCollection();

    // create some object that we will add to collection
    var obj1 : Object = { name : "Object1" };
    var obj2 : Object = { name : "Object2" };
    var obj3 : Object = { name : "Object3" };

    // add those objects to collection
    arrayCollection.addItem( obj1 );
    arrayCollection.addItem( obj2 );
    arrayCollection.addItem( obj3 );

    // and now let's create a new object that we will want add instead of obj2
    var obj4 : Object = { name : "Object4" };

    // lets say that we don't remember that index of obj2 in a collection is "1". We have to get from collection
    var obj2Index : int = arrayCollection.getItemIndex( obj2 );

    trace( obj2Index ) // 1

    // now when we know index we can replace obj2 with obj4
    arrayCollection.setItemAt( obj4, obj2Index );

    // now when we have replaced values we can see that item at index "1" property "name" is "Object4"
    trace( arrayCollection.getItemAt( obj2Index )["name"] ) // "Object4"

}