Flex arraycollection getitemindex始终返回-1

时间:2011-12-21 05:05:51

标签: actionscript-3 flex arraycollection

我面临同样的问题。有人可以用一个例子来解释我吗?

我的代码是:

var dataList:ArrayCollection = new ArrayCollection([{name:"alauddn"}, {name:"ansari"}]);

private function getItemInd(event:MouseEvent):void{

    var item:Object = new Object();
    item.name = "ansari";
    var ias:int = dataList.getItemIndex(item);
    Alert.show(ias.toString() + ": " + item.name);
}

但它返回“ -1

3 个答案:

答案 0 :(得分:7)

getItemIndex不会比较arrayCollection中的值。问题是getItemIndex()方法匹配精确的对象引用,而不匹配具有匹配属性的对象。

您应该使用这样的解决方案:

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="creationCompleteHandler(event)">

    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import mx.controls.Alert;
            import mx.events.FlexEvent;

            public var dataList:ArrayCollection = new ArrayCollection([{name:"alauddn"}, {name:"ansari"}]);

            public function getItemIndexByProperty(array:ArrayCollection, property:String, value:String):Number
            {
                for (var i:Number = 0; i < array.length; i++)
                {
                    var obj:Object = Object(array[i])
                    if (obj[property] == value)
                        return i;
                }
                return -1;

                dataList.getItemIndex();
            }

            protected function creationCompleteHandler(event:FlexEvent):void
            {
                var ias:int = getItemIndexByProperty(dataList, "name", "ansari");
                Alert.show(ias.toString() + " : " + dataList.getItemAt(ias).name);
            }

        ]]>
    </fx:Script>

</s:WindowedApplication>

答案 1 :(得分:0)

getItemIndex仅搜索根对象。例如,这可行:

var dataList:ArrayCollection = new ArrayCollection(["alauddn", "ansari"]);

private function getItemInd(event:MouseEvent):void{
    var name:String = "ansari";
    var ias:int = dataList.getItemIndex(name);
    Alert.show(ias.toString() + ": " + name);
}

答案 2 :(得分:0)

你可以使用它。

private function getItemInd(event:MouseEvent):void{
for each( var item:Object in dataList){    
if(item.name == "ansari")
{
var ias:int = dataList.getItemIndex(item);
Alert.show(ias.toString() + ": " + item.name);
break;
}
}
}