使用堆栈卡加载数组

时间:2011-07-04 11:44:17

标签: javascript

我想要一种方法来加载数组中的52张卡,而无需对其进行硬编码。 我有一个数组suits,其中包含每个套装的“H”,“C”,“S”,“D”前缀。 我需要一个数组cards[52],其值为H1-H13,S1-S13等。 我面临的问题是我可以很轻松地将cards[0]加载到cards[12],但如何在cards[13]中加载下一张卡?

4 个答案:

答案 0 :(得分:2)

您可以这样做:

var suits = new Array("H", "C", "S", "D");
var cards = new Array();
// changed 3 to 4 to display all four suits
var cnt = 0;
for(i=0; i<4; i++)
    for(j=1; j<=13; j++)
        cards[cnt++] = suits[i] + j;

答案 1 :(得分:0)

您可以将所有52张卡片加载到一个阵列中,如您所想:

var suits = ['H', 'C', 'S', 'D'];
var cards = [];
var suitIndex = 0;

for(var i = 0 i < 52; i++) {
  cards.push(suits[suitIndex] + (i % 13));

  // if remainder after division by 13 is zero, 
  // you know you've hit a multiple of 13 and need to switch suits.
  if (i % 13 == 0 && suitIndex < suits.length) {
    suitIndex++;
  }
}

或者,您可以创建4个不同的卡阵列,并在填充时插入不同的阵列。

答案 2 :(得分:0)

尝试:

var suits = ["H", "C", "S", "D"], cards = [], n = 0;
while(n < 4){
    for(i = 1; i < 13; i++)
        cards.push(suits[n] + i);
    n++;
}

答案 3 :(得分:0)

坦率地说,没有任何充分的理由可以动态生成套牌,只需手动操作即可快速生成套牌:

var cards = [
  "H1", "H2", "H3",  "H4",  "H5",  "H6", "H7",
  "H8", "H9", "H10", "H11", "H12", "H13",
  "C1", "C2", "C3",  "C4",  "C5",  "C6", "C7",
  "C8", "C9", "C10", "C11", "C12", "C13",
  "S1", "S2", "S3",  "S4",  "S5",  "S6", "S7",
  "S8", "S9", "S10", "S11", "S12", "S13",
  "D1", "D2", "D3",  "D4",  "D5",  "D6", "D7",
  "D8", "D9", "D10", "D11", "D12", "D13"
]