Flex arraycollection gettitemindex总是返回-1



我也面临同样的问题。有人能举个例子解释一下吗?

我的代码是:
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:

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>

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

你可以使用这个

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

相关内容

  • 没有找到相关文章

最新更新