Calculating Dictionary length in Flex

元气小坏坏 提交于 2019-12-23 08:56:44

问题


What's 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 any way to do it other than looping through the objects?


回答1:


No, there is no way to check the length of an object(Dictionary is pretty much an object that supports non-String keys) other than looping through the elements.

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

You probably don't have to worry about checking if the property is an internal one.




回答2:


There's a util function in as3corelib which can get the keys in the dictionary. You can check out DicitonaryUtil

The method is:

    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:


You can use associative arrays instead because I don't think it's possible to check the length of a Dictionary object. You could however extend the Dictionary class and add that functionality and override the corresponding methods.

Alternatively, you could loop through it each time to get the length which isn't really a good idea but is available.

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 the "setPropertyIsEnumerable" but I believe that's more useful for objects than it is for Dictionary.




回答4:


You could write a class around a dictionnary that controls insertions/removals so you can keep track of the key count.

Try extending proxy or just do a wrapper.




回答5:


For anyone stumbling upon this now there is an update to DictionaryUtil. You can now just call..

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



回答6:


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

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


来源:https://stackoverflow.com/questions/707354/calculating-dictionary-length-in-flex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!