ActionScript对象名称的变量

时间:2012-08-07 10:13:40

标签: flex actionscript

在这个例子中:

var poets:Array = new Array();
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});

'name'和'born'是否可能是变量?

2 个答案:

答案 0 :(得分:1)

正如@RIAstar指出的那样,它们是'关联数组'的属性 - 动态对象{}

var poets:Array = new Array();
poets.push({"name":"test","born":"1928"});
poets.push({name:"Angelou", born:"1928"});
poets.push({name:"Blake", born:"1757"});
poets.push({name:"cummings", born:"1894"});
poets.push({name:"Dante", born:"1265"});
poets.push({name:"Wang", born:"701"});

trace(poets[0].name,poets[0].born);

或更广泛的版本:

var prop1:String = "name";
var prop2:String = "born";
var poets:Array = [];
poets[0] = {};
poets[0][prop1] = "test2";
poets[0][prop2] = "1900";

trace(poets[0].name,poets[0].born);

答案 1 :(得分:0)

如果要创建一个返回给定属性名称的数据的函数,可以执行以下操作:

        public function getDataByAttribute(fieldName:String):Array {
            return poets.map(
                function (item:*, index:int, array:Array):String {
                    return item[fieldName];                         
                }   
            );
        }

        // sample call  
        var results:Array = getDataByAttribute("born");

您可以根据自己的需要进行修改。

要探索Array的功能,请参阅此blog(不是我的)。