Get size of ActionScript 3 Dictionary

Bart van Heukelom picture Bart van Heukelom · Mar 5, 2010 · Viewed 20.9k times · Source
var d:Dictionary = new Dictionary();
d["a"] = "b";
d["b"] = "z";

How to get the length/size of the dictionary (which is 2) ?

Answer

M.A. Hanin picture M.A. Hanin · Mar 5, 2010

There is no built-in method to get the size/lenght/count of an AS3 dictionary. There are workarounds: for example, you can create a custom dictionary class which extends or wraps the flash.utils.Dictionary class, adding the counter functionality. You can manage the count as entries are added/removed, or count on-demand using a simple For loop iteration:

public static function countKeys(myDictionary:flash.utils.Dictionary):int 
{
    var n:int = 0;
    for (var key:* in myDictionary) {
        n++;
    }
    return n;
}