Actionscript使用稀疏数组,因此我可以使用这样的数组:
var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";
现在myArray.length会给我23.有没有办法在不迭代每个元素的情况下获得数组中的实际项目数?
答案 0 :(得分:1)
使用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--;
}
}
答案 1 :(得分:1)
如果您不想遍历数组,可以对其进行过滤:
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 != "";
}
答案 2 :(得分:1)
最快的方法应该是始终使用内置函数。
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