AS3 数组问题

AS3 Array Issue

我是一名 AS3 新手,正在开发我的第一款游戏。

所以我有一个部队阵列,从商店购买时会添加。

public var myTroops: Array = [{type: "lightInfantry", hp: "100", def: "10"},
{type: "lightInfantry", hp: "100", def: "10"},
{type: "heavyInfantry", hp: "100", def: "10"}];

我需要找到某种类型的步兵出现了多少次然后追溯,我发现其他问题求助,但不是多阵列。我怎么会得到这个?基本上是在如何编写返回玩家已经拥有的每个步兵数量的代码方面寻求一些帮助。

非常感谢提示和回答。提前致谢。

首先,让您的生活更轻松,并保持一些常量。这提供了针对拼写错误的编译时间检查,因此您只需输入一次字符串。

package {
   public class TROOP_TYPE {
       public const LIGHT_INFANTRY:String = "lightInfantry";
       public const HEAVY_INFANTRY:String = "heavyInfantry";
   }
}

现在,您可以制作一个辅助函数来计算某些类型:

public function countTroops(type:String):int {
    var ctr:int = 0; 

    //loop through the troops array
    for(var i:int=0;i<myTroops.length;i++){
        //if the current troop matches the type passed, increment the counter
        if(myTroops[i].type == type) ctr++;
    }

    //return the value
    return ctr;
}

然后这样称呼它:

var lightCount:int = countTroops(TROOP_TYPE.LIGHT_INFANTRY);