如何访问 AS3 中的对象

How to access an object in AS3

这段代码是我写的

var enemies:Object = new Object();
//                HP  MP  ATK  DEF  MATK   MDEF  AGI  LUCK
enemies.Goblin = [40, 20,  6,   6,    3,     3,   4,   1];

其中包含地精的那些统计数据,我创建了一个函数,该函数应该从 enemies.Goblin 中获取统计数据并将它们放入一些变量中,但它不起作用。

function createEnemy(enemyName:String):void {

e_hp = enemies.enemyName[0];
e_mp = enemies.enemyName[1];
e_atk = enemies.enemyName[2];
e_def = enemies.enemyName[3];
e_matk = enemies.enemyName[4];
e_mdef = enemies.enemyName[5];
e_agi = enemies.enemyName[6];
e_luck = enemies.enemyName[7];

}

这是执行 createEnemy 函数时的输出错误:TypeError: Error #1010: A term is undefined and has no properties.

对象 "enemies" 没有 "enemyName" 属性。 试试这个:

enemies[enemyName][0]
enemies[enemyName][1]
...

将对象(所有内容)存储在数组中以便于引用。下面是关键代码:

var aEnemies:Array = new Array();
var mcEnemy:Object = new Object();

mcEnemy.iHP = 40;  //  set iHP property to 40

aEnemies.push(mcEnemy);  //  add enemy to array of enemies

trace("enemy 0's HP: " + aEnemies[0].iHP);

答案已经给出,但是你的做法是错误的。通过索引访问属性在不久的将来会遇到麻烦。

最好用类,但既然你在使用对象,我也会尝试使用对象:

var goblin_stats:Object = { hp:40, mp:20, atk:6, def:6 }; // and so on
var elf_stats:Object = { hp:35, mp:30, atk:8, def:4 }; // and so on
...
// add as much characters as needed

现在我相信你只是想根据地精统计数据创建一个新的地精。只需将统计数据传递给 createEnemy 函数即可:

createEnemy(goblin_stats);

function createEnemy(stats:Object):void {
    e_hp = stats.hp;
    e_mp = stats.mp;
    // and so on
}

或更好:

function createEnemy(stats:Object):void {
    for (var property:String in stats) e_stats[property] = stats[property];
}