Flash CS4 [AS3]:使用循环生成数组

时间:2009-12-15 03:58:31

标签: flash actionscript-3 arrays loops

下面我有一个有效的数组,但它太长了,我想有一个更简单的方法来使用循环生成相同的结果但是我现在无法理解它。数组如下:

var CardDeck = new Array();
CardDeck[0] = new C1();
CardDeck[1] = new C2();
CardDeck[2] = new C3();
CardDeck[3] = new C4();
CardDeck[4] = new C5();
CardDeck[5] = new C6();
CardDeck[6] = new C7();
CardDeck[7] = new C8();
CardDeck[8] = new C9();
CardDeck[9] = new C10();
CardDeck[10] = new C11();
CardDeck[11] = new C12();
CardDeck[12] = new C13();
CardDeck[13] = new D1();
CardDeck[14] = new D2();
CardDeck[15] = new D3();
CardDeck[16] = new D4();
CardDeck[17] = new D5();
CardDeck[18] = new D6();
CardDeck[19] = new D7();
CardDeck[20] = new D8();
CardDeck[21] = new D9();
CardDeck[22] = new D10();
CardDeck[23] = new D11();
CardDeck[24] = new D12();
CardDeck[25] = new D13();
CardDeck[26] = new H1();
CardDeck[27] = new H2();
CardDeck[28] = new H3();
CardDeck[29] = new H4();
CardDeck[30] = new H5();
CardDeck[31] = new H6();
CardDeck[32] = new H7();
CardDeck[33] = new H8();
CardDeck[34] = new H9();
CardDeck[35] = new H10();
CardDeck[36] = new H11();
CardDeck[37] = new H12();
CardDeck[38] = new H13();
CardDeck[39] = new S1();
CardDeck[40] = new S2();
CardDeck[41] = new S3();
CardDeck[42] = new S4();
CardDeck[43] = new S5();
CardDeck[44] = new S6();
CardDeck[45] = new S7();
CardDeck[46] = new S8();
CardDeck[47] = new S9();
CardDeck[48] = new S10();
CardDeck[49] = new S11();
CardDeck[50] = new S12();
CardDeck[51] = new S13();

有人可以告诉我如何将它们放在一个可以产生相同结果的循环中吗?

由于 本

2 个答案:

答案 0 :(得分:3)

您可以使用getDefinitionByName来获取对编号卡类的引用,如下所示:

import flash.utils.getDefinitionByName;

var deck:Array = [];
var suits:Array = ['C', 'D', 'H', 'S'];
var card:Class;

for each(var suit:String in suits) {
    for(var i:int = 1; i <= 13; i++) {
        card = getDefinitionByName(suit + i) as Class;
        deck.push(new card());
    }
}

答案 1 :(得分:1)

这段代码可能无法正常工作(我对AS3有点生疏),但经过一些调整,它应该引导你朝着正确的方向前进:

public class Card {
    var suit:String;
    var value:int;

    public Card(Suit:String, Value:int)
    {
        this.suit = Suit;
        this.value = Value;
    }
} 

public class Deck {
    var deck:Array = new Array();
    var suits:Array = new Array('C', 'D', 'H', 'S');

    for (var x = 0; x < 52; x++) {
        deck[x] = new Card(suits[x / 13], x % 13);
    }
}

现在我对卡片声明不感兴趣(我没有通过编译来检查我的语法的Flash副本),但是“deck [x] = new Card ...”行应该是什么要做的是将前13个卡套装设置为C,将第二个13套装设置为D等,并将值设置为0到13(意味着Ace = 0,2 = 1,3 = 2,...,K = 12)。

希望这是有道理的(我希望你不必过多地调整它以使它适合你)。