首页 > 设计 > WEB开发 > 正文

13.1.为ArrayCollection添加,排序和获取数据

2023-07-22 12:39:16
字体:
来源:转载
供稿:网友
13.1.1. 问题
我需要添加新数据到ArrayCollection 以及从同一个ArrayCollection 中获取某个数据。
13.1.2. 解决办法
创建ArrayCollection , 使用addItemAt 或addItem 方法插入对象到ArrayCollection ,getItemIndex 或contains 方法用于检测数据项是否已存在于数组中,而ArrayCollection 的sort属性是对ArrayCollection排序以及通过某个字段决定接收第一个或最后一个数据。
13.1.3. 讨论
为了了解ArrayCollection 中添加,测试,排序数据项的各种方法是如何工作的,首先创建一个ArrayCollection,类似如下的代码:
+展开
-XML
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxmlwidth="400"
height="300creationComplete="init()">

<mx:Script>
<![CDATA[
import mx.collections.SortField;
import mx.collections.Sort;
import mx.collections.ArrayCollection;
private var coll:ArrayCollection;
private function init():void {
coll = new ArrayCollection(
[{name:"Martin Foo", age:25},
{name:"Joe Bar", age:15},
{name:"John Baz", age:23}]);
}
</mx:VBox>

要插入元素到指定位置,可使用addItemAt 方法:
+展开
-ActionScript
private function addItem():void {
coll.addItemAt({name:"James Fez", age:40}, 0);
}

要检查ArrayCollection 中是否已存在复杂对象,你需要比较两个对象的值:
+展开
-ActionScript
private function checkExistence():void {
trace(coll.contains({name:nameTI.text,age:Number(ageTI.text)}));
trace(coll.getItemIndex({name:nameTI.text, age:ageTI.text}));
// traces -1 if not present
}

但是上面的做法是不对的,因为contains 和getItemIndex 方法都是比较对象的指针,而不是他们的值。因为两个对象是截然不同的对象,因为存在于内存的不同位置, Flash Player 认为他们是不相等的。即便ArrayCollection 包含该元素,但getItemIndex 方法也不会返回其索引值。要检测元素是否具有相同的值,你需要和所有的数据对象进行值比较:
+展开
-ActionScript
private function checkExistence():int {
var i:int;
var arr:Array = coll.souce;
while(i < arr.length) {
if(arr[i].name == nameTI.text && arr[i].age ==
ageTI.text) {
return i;
}
i++;
}
return -1;
}

Sort 对象提供findItem 方法用于搜索这个ArrayCollection 中的所有元素。方法原型如下:
public function findItem(items:Array, values:Object, mode:String,
returnInsertionIndex:Boolean = false, compareFunction:Function = null):int


Value 参数可以是包含属性和所需值的任何对象。Mode 字符串可以是
Sort.ANY_INDEX_MODE,表示返回任何匹配项索引,Sort.FIRST_INDEX_MODE 表示返回第一个匹配项索引, Sort.LAST_INDEX_MODE 表示返回最后一个匹配项索引。
returnInsertionIndex 参数表示如果该方法找不到由values 参数标识的项目,并且此参数为true,则findItem() 方法将返回这些值的插入点,也就是排序顺序中应插入此项目的。
compareFunction 设置用于查找该项目的比较运算符函数.

使用Sort 对象的findItem 方法代替上面的方法:
+展开
-ActionScript
private function checkExistence():int {
var sort:Sort = new Sort();
return sort.findItem(coll.source,{name:nameTI.text, age:Number(ageTI.text)},
Sort.ANY_INDEX_MODE);
}

首先要创建一个Sort,传递一个SortField 对象数组给fields 属性。这些SortField 对象包含的字符串正是每个ArrayCollection 元素将要用来排序的属性。如要对每个对象的age 属性进行排序,创建Sort 对象,传递SortField,设置排序字段为age:
+展开
-ActionScript
private function getOldest():void {
var sort:Sort = new Sort();
sort.fields = [new SortField("age"false)];
coll.sort = sort;
coll.refresh();
trace(coll.getItemAt(0).age+" "+coll.getItemAt(0).name);
}

这个排序函数对age 值从低向高排序。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表