通过 [String][String] 嵌套 Array/Object 访问

Nested Array/Object access via [String][String]

在 AS3 中,我可以按如下方式访问嵌套的 array/object:

var platformObj:Object = {"filters": {"manufacturer": ["Adobe Windows"]};
trace(platformObj["filters"]["manufacturer"]); //trace output: "Adobe Windows";

Haxe 中的错误:字符串应为 Int(对于第二个参数):
platformObj["filters"]["manufacturer"]

如何在 Haxe/OpenFL 中执行此操作?

openfl.utils.Object 基本上只是 Dynamictypedef,所以以下工作正常:

trace(platformObj.filters.manufacturer); // [trace] Main.hx:6: [Adobe Windows]

如果您需要使用String访问字段,您可以使用type check执行以下操作:

trace((platformObj["filters"] : Object)["manufacturer"]);

在幕后,所有这些只是 reflection:

trace(Reflect.field(Reflect.field(platformObj, "filters"), "manufacturer"));

您可以只使用点符号:

var platformObj = {filters: {manufacturer: ["Adobe Windows"]}};
// the type of platformObj is `{filters:{manufacturer:Array<String>}}` in this case
trace(platformObj.filters.manufacturer);

或者您可以使用 StringMap

var platformObj = ["filters" => ["manufacturer" => ["Adobe Windows"]]];
// the type of platformObj is `Map<String, Map<String, Array<String>>>` in this case
trace(platformObj["filters"]["manufacturer"]);

Haxe 没有 Object,但有 Dynamic. You can retrieve its fields using Reflect:

var platformObj:Dynamic = {filters: {manufacturer: ["Adobe Windows"]}};
var filters = Reflect.field(platformObj, "filters");
var manufacturer = Reflect.field(filters , "manufacturer");
trace(manufacturer);

当您使用 Haxe 3.3+ 时,您可以使用 Any 而不是 Dynamic

前两个用起来比较安全。最后一个使用 dynamic/reflection 可能会有副作用。