Calculating Dictionary Length in Flex

What is the best way to calculate the length of a Dictionary object in Flex?

var d:Dictionary = new Dictionary(); d["a"] = "alpha"; d["b"] = "beta"; 

I want to check the length, which should be 2 for this Dictionary. Is there a way to do this differently than sorting through objects?

+7
flex actionscript-3 flex3
source share
6 answers

No, there is no way to check the length of an object (A dictionary is pretty much an object that supports keys other than String), except that it cycles through the elements.

http://www.flexer.info/2008/07/31/how-to-find-an-objects-length/

You probably don't need to worry about checking if the property is internal.

+12
source share

There is a util function in as3corelib that can get keys in a dictionary. You can check out DicitonaryUtil

Method:

  public static function getKeys(d:Dictionary):Array { var a:Array = new Array(); for (var key:Object in d) { a.push(key); } return a; } 

So you would do getKeys (dictionary) .length

+3
source share

You can use associative arrays because I don't think you can check the length of a Dictionary object. However, you can extend the dictionary class and add this functionality and override the appropriate methods.

Alternatively, you can scroll it every time to get a length that is not really a good idea, but affordable.

 var d:Dictionary = new Dictionary(); d["hi"] = "you" d["a"] = "b" for (var obj:Object in d) { trace(obj); } // Prints "hi" and "a" 

You can also look here for information on using "setPropertyIsEnumerable", but I find this more useful for objects than for a dictionary.

+1
source share

You can write a class around dictionnary that controls insertions / deletions so you can keep track of the number of keys.

Try to expand the proxy server or just do a wrapper.

0
source share

For those who stumble upon this now, there is an update for DictionaryUtil. Now you can just call ..

 var count:int = DictionaryUtil.getKeyCount(myDictionary); 
0
source share

You can get the keys Dictionary and check the length keys array , as shown below:

 var d:Dictionary = new Dictionary(); d["a"] = "alpha"; d["b"] = "beta"; var count:int = DictionaryUtil.getKeys(d).length; 
0
source share

All Articles