尝试在循环中创建类的新实例,其中已在数组中定义类实例名称。如何将数组值从字符串转换为对象?这是我到目前为止所写的内容
var tiles2:Array = new Array("e1", "e2", "e3", ...);
for (var i = 0; i < tiles2.length; i++){
if (i == 0){
xPos = 18;
}else if (xPos > 0 && xPos < maxGridWidth){
xPos =+ xPos + objWidth + horGap;
//trace(xPos);
}else{
xPos = 18;
yPos =+ yPos + verGap + objHeight;
}
var this[tiles2[i]] = new tiles2[i];
this[tiles2[i]].name = tiles2[i];
this[tiles2[i]].x = xPos;
this[tiles2[i]].y = yPos;
tileArray[i] = this[tiles2[i]];
addChild(this[tiles2[i]]);
}
这是我遇到问题的地方var mc = new tiles2[i];
。我期望的输出就像是
var e1 = new e1;
e1.name = tiles2[i];
e1.x = xPos;
e1.y = yPos;
tileArray[i] = e1;
addChild(e1);
如果你有更好的程序,我会很高兴,如果你能告诉我
答案 0 :(得分:1)
我相信你正在寻找这个...
// If tiles2[i] is a string that is the name of a class
var type:Class = getDefinitionByName(tiles2[i]) as Class;
var thing = new type();
// If tiles2[i] is a string instance name for an existing object:
var thing:DisplayObject = getChildByName(tiles[i]);
或者,您可能只需将相关行更改为:
//var mc = new tiles2[i]; <-- line in question
//take out the var, and instantiate the proper class
this[tiles2[i]] = new e1();