【问题标题】:Create an associative array with dynamic keys in Actionscript 2在 Actionscript 2 中使用动态键创建关联数组
【发布时间】:2009-08-02 13:41:56
【问题描述】:

对于 XML 文件,我想在 actionscript 中创建一个数组,我可以在其中使用我设置的键而不是 0、1、2 等来引用特定值

buildings = myParsedObjectFromXML;

var aBuildings = new Array();

for ( building in buildings ) {
    var currentBuilding = buildings[building][0];
    var key:String = currentBuilding.buildingCode;

    aBuildings[key][property1] = currentBuilding.someOtherValue;
    aBuildings[key][property2] = currentBuilding.aDifferentValue;
    ... etc
}

这样我以后可以像这样访问数据:

// building description
trace( aBuildings[BUILDING1][property2] );

但上述方法不起作用 - 我错过了什么?

【问题讨论】:

    标签: arrays actionscript actionscript-2 associative-array


    【解决方案1】:

    我首先将我的 aBuildings 变量实例化为一个对象而不是一个数组:

    var aBuildings = new Object();
    

    接下来,您需要先为要在其中存储属性的键创建一个对象。

    aBuildings[key] = new Object();
    aBuildings[key]["property1"] = currentBuilding.someOtherValue;
    aBuildings[key]["property2"] = currentBuilding.aDifferentValue;
    

    那么您应该能够从 aBuildings 对象中读取值:

    trace( aBuildings["BUILDING1"]["property2"] );
    

    请记住,如果 BUILDING1 和 property2 不是字符串变量,则需要使用字符串字面量。

    【讨论】:

    • +1。关联的“数组”没有任何有用的目的AFAIK。如果您想要数字排序,请使用数组。如果要通过键访问,请使用对象。 “{}”也是“new Object()”的快捷方式
    • @Chetan Sastry:Actionscript 中的对象是关联数组 :)
    猜你喜欢
    • 2010-09-25
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多