动作中的动态变量3

时间:2016-09-12 10:36:55

标签: actionscript-3 variables dynamic

我正在编写矿石计算器,为此,我有重复的变量 - 名称如下:

tritaniumlogo:MineralContainer:new MineralContainer(values)
tritaniumtext:MinText=new MinText(values)

MineralcontainerMinText是一些已定义的类。自从我重复自己以来,我试图重新考虑80行代码。

所以我使用以下代码创建了一个Array来保存一些数据,但它不起作用:

private var minsVar:Array = [[50, 98, "Tritanium", emptySpace], [50, 134, "Pyerite", emptySpace], [50, 170, "Mexallon", emptySpace], [50, 206, "Isogen", emptySpace], [230, 98, "Noxcium", emptySpace], [230, 134, "Zydrine", emptySpace], [230, 170, "Megacyte", emptySpace], [230, 206, "Morphite", emptySpace]];

for (var a:int = 0; a < minsVar.length; a++) {  
    private var [minsVar[a][2] + "logo"] = new MineralContainer(minsvar[a][0], minsvar[a][1], a + 1);
    private var [minsVar[a][2] + "textinput"] = new MinText(minsvar[a][0], minsvar[a][1], minsvar[a][2], minsvar[a][3]);
}

1 个答案:

答案 0 :(得分:0)

如果循环在类方法中,那么您可以执行以下操作:

for (var a:int = 0; a < minsVar.length; a++) {
    this[minsVar[a][2] + "Logo"] = new MineralContainer(minsvar[a][0], minsvar[a][1], a + 1);
    this[minsVar[a][2] + "Textinput"] = new MinText(minsvar[a][0], minsvar[a][1], minsvar[a][2], minsvar[a][3]);
}

然后,您可以使用this["TritaniumLogo"]this["PyeriteTextinput"]来访问它们。但是,最好将“新”对象存储在某些关联数组中:

private var minsVar:Array = [[50, 98, "Tritanium", emptySpace], [50, 134, "Pyerite", emptySpace], [50, 170, "Mexallon", emptySpace], [50, 206, "Isogen", emptySpace], [230, 98, "Noxcium", emptySpace], [230, 134, "Zydrine", emptySpace], [230, 170, "Megacyte", emptySpace], [230, 206, "Morphite", emptySpace]];

private var arrLogoes:Array = new Array();
private var arrTextInputs:Array = new Array();
// ...
for (var a:int = 0; a < minsVar.length; a++) {
    arrLogoes[minsVar[a][2]] = new MineralContainer(minsvar[a][0], minsvar[a][1], a + 1);
    arrTextInputs[minsVar[a][2]] = new MinText(minsvar[a][0], minsvar[a][1], minsvar[a][2], minsvar[a][3]);
}

例如,您可以稍后使用arrLogoes["Tritanium"]arrTextInputs["Pyerite"]访问它们。