我正在尝试为游戏生成纸牌。
当我打印出数组时,为什么排列不整齐?
预期产量:

 [
        {number: 1, suite: "Hearts", points: 1},
        {number: 2, suite: "Hearts", points: 2},
        ...
    ]


打印出来的结果是:

[
    {number: 2, suite: "Hearts", points: 2},
    {number: 4, suite: "Hearts", points: 4},
    {number: 13, suite: "Clubs", points: 10},
    {number: 5, suite: "Diamonds", points: 5},
    {number: 4, suite: "Spades", points: 4},
    {number: 13, suite: "Diamonds", points: 10},
    ...
]


我不确定为什么会这样...我该如何解决订单?

对象数组通常不按顺序排列吗?



function generateCards() {
  deck = []
  let i = 1;
  let j = 1;
  for (j = 1; j < 5; j++) {
    let suite = ""
    switch (j) {
      case (1):
        suite = "Hearts"
        break;
      case (2):
        suite = "Diamonds"
        break;
      case (3):
        suite = "Clubs"
        break;
      case (4):
        suite = "Spades"
        break;
    }
    for (i = 1; i < 14; i++) {
      switch (i) {
        case (11):
          points = 10;
          break;
        case (12):
          points = 10;
          break;
        case (13):
          points = 10;
          break;
        default:
          points = i;
          break;
      }
      card = {
        "number": i,
        "suite": suite,
        "points": points
      }
      deck.push(card)
    }
  }
  console.log(deck)
  return deck;
}


generateCards();

最佳答案

这不会解决订单问题(我无法重现),但是会大大缩短您的代码。



function generateCards() {
  const suites = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
  const deck = []

  for (let j = 0; j < 4; j++) {
    for (let i = 1; i < 14; i++) {
      deck.push({
        number: i,
        suite: suites[j],
        points: i >= 11 ? 10 : i
      });
    }
  }

  return deck;
}


console.log(generateCards());





您甚至可以将其压缩为一个循环:



function generateCards() {
  const suites = ['Hearts', 'Diamonds', 'Clubs', 'Spades'];
  const deck = []

  for (let i = 0; i < 52; i++) {
    const number = i % 13 + 1;

    deck.push({
      number,
      suite: suites[i / 13 | 0], // divide by 13 and round down
      points: number >= 11 ? 10 : number
    });
  }

  return deck;
}


console.log(generateCards());

关于javascript - 阵列未按顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47368779/

10-12 06:43