如何动态访问对象属性?

时间:2011-01-25 22:40:44

标签: actionscript-3 object-property

我已将对象属性的名称存储为字符串。在PHP中,如果对象名为$object且属性变量名为$key,则可以使用$object->$key访问它。如何在ActionScript中动态访问属性?

2 个答案:

答案 0 :(得分:7)

你可以像这样访问它:

var obj = {
    property1: 'this is a property',
    property2: 'this is another property'
}
var key = 'property2';

obj[key]; // 'this is another property'

答案 1 :(得分:2)

您可以通过点运算符或数组访问运算符访问对象中的值和属性:

var myObject:Object = new Object();
myObject.propString = "I'm a String";
myObject.propNumber = 22;
myObject.propObject = {keyOne: "Key String", keyTwo: 23};

trace(myObject["propString"], myObject.propNumber);  //I'm a String 22
trace(myObject.propObject.keyOne, myObject.propObject["keyTwo"]); //Key String 23

上面的 myObject 变量也可以这样写:

var myObject:Object = {propString: "I'm a String", propNumber: 22, propObject: {keyOne: "Key String", keyTwo: 23}};