문제

Actionscript uses sparse arrays, so I can have an array like this:

var myArray:Array = new Array();
myArray[0] = "foo";
myArray[22] = "bar";

Now myArray.length will give me 23. Is there a way to get the actual number of items in the array without iterating every element?

도움이 되었습니까?

해결책

If you don't want to iterate through the array, you can filter it:

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 != "";
}

다른 팁

By using for syntax, which will iterate the definded indexes:

public static function definedCount(arr:Array):uint {
    var ctr:uint = 0;
    for(ix:* in arr)
        ctr++;
    return ctr;
}

If you need to frequently check the count of items in a sparse array, you should wrap it an a collection class that independently keeps track of the count of items. Something like:

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

Fastest method should be to always use the inbuilt functions.

    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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top