Actionscript使用稀疏数组,所以我可以有这样的数组:
var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";
现在myArray.length会给我23。有没有一种方法可以在不迭代每个元素的情况下获得数组中的实际项数?
如果你不想遍历数组,你可以过滤它:
var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";
var numberOfItems:int = myArray.toString().split(',').filter(isItem).length;
function isItem(item:*, index:int, array:Array):Boolean
{
return item != "";
}
通过使用for
语法,它将迭代定义的索引:
public static function definedCount(arr:Array):uint {
var ctr:uint = 0;
for(ix:* in arr)
ctr++;
return ctr;
}
如果需要经常检查稀疏数组中的项数,则应该将其包装为一个独立跟踪项数的集合类。类似于:
public class IndexedCollection {
private var _arr:Array = [];
private var _itemCount:uint = 0;
public function get count():uint {
return _itemCount;
}
public function getItem(index:uint):* {
return _arr[index];
}
public function setItem(index:uint, value:*):void {
if(_arr[index] === undefined)
_itemCount++;
_arr[index] = value;
}
public function delete(index:uint):void {
if(_arr[index] === undefined)
return;
delete _arr[index];
_itemCount--;
}
}
最快的方法应该始终使用内置函数。
function myFilter(item:*, index:int, array:Array):Boolean{
if(item)
{
return true;
}else{
return false;
}
}
var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";
trace(myArray.length) // 23
var myMyNewArray:Array = myArray.filter(myFilter)
trace(myMyNewArray .length) // 2