FLEX:你如何获得数组的关键名称?数组的键名?

时间:2011-03-14 10:39:31

标签: arrays flex key

我一直在搜索如何获取flex数组的键名,因为Array类中没有这样的函数。这是我的回答,可能对你们任何人都有用。

2 个答案:

答案 0 :(得分:2)

试试这个:

        protected function getArrayKeys(a:Array):void
        {
            for (var key:String in a)
            {
                trace (key);
            }
        }

编辑:

我创建了示例应用程序来演示关联数组

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
               creationComplete="application1_creationCompleteHandler(event)"
               >
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;


            protected function application1_creationCompleteHandler(event:FlexEvent):void
            {
                var o1:Object = new Object();
                var o2:Object = new Object();

                //these access methods are equivalent:

                //By property
                o1.x = "Object1 xValue";
                o1.y = "Object1 yValue";

                //By indexer
                o2["x"] = "Object2 xValue";
                o2["y"] = "Object2 yValue";

                //Access object properties by name
                trace (o1.x);
                trace (o1.y);

                trace (o2.x);               
                trace (o2.y);               

                //dumpObject uses indexer to access key values
                dumpObject(o1);
                dumpObject(o2);

            }

            protected function dumpObject(o:Object):void
            {
                for (var key:String in o)
                {
                    //loop through property names and access values by indexer.
                    trace ("Key = " + key + ". Value = " + o[key]);
                }
            }

        ]]>
    </fx:Script>

</s:Application>

另请注意,使用Object时,您将被限制为String类型的键。您可以使用字典类而不是字符串类型的关键字类型的关联数组。

答案 1 :(得分:1)

    import mx.utils.ObjectUtil;

    var __arCurrent:Array=new Array();
    __arCurrent["x"]=10;
    __arCurrent["y"]=20;

    //Get class info of __arCurrent to get the keys name of the array
    var classInfoArray:Object=ObjectUtil.getClassInfo(__arCurrent);

    //For each key of the array __arCurrent
    for(var i:int=0;i<classInfoArray.properties.length;i++){
        var keyname:String = classInfoArray.properties[i].localName;
    }