简体   繁体   English

array.includes问题

[英]array.includes issue

So my issue seems to be that the getNumString() method is not operating correctly because the while loop goes on indefinitely, but I can't seem to figure out why. 所以我的问题似乎是getNumString()方法不能正确运行,因为while循环会无限期地进行,但是我似乎无法弄清楚为什么。 The deck is supposed to be filled with the example strings you see inside of that but it never calls any of them but the first when the while loop does not go indefinitely (with some changes to the code of course). 甲板上应该填充了您在其中看到的示例字符串,但从未调用任何一个,而是在while循环不会无限期进行时(当然,对代码进行了一些更改),第一个未调用。 Any insight would be greatly appreciated. 任何见识将不胜感激。

let deck = [
    //"cardR01C01", "cardR01C01",
  ];

function getNumString(num) {
  if (num < 10) {
    return "0" + num.toString();
  }
  else {
    return num.toString();
  }
}

function getRandomNum(upperLimit) {
  return Math.floor((Math.random() * upperLimit) + 1);
}

function fillDeck() {
  let cardString = ".cardR" + getNumString(getRandomNum(4)) + "C" +
    getNumString(getNumString(13));
  while (deck.includes(cardString)) {
    cardString = ".cardR" + getNumString(getRandomNum(4)) + "C" +
      getNumString(getNumString(13));
  }
  deck.push(cardString);
  deck.push(cardString);
}

for (let i = 0; i < (numCards / 2); i++) {
  fillDeck();
}

*After a bit more testing I've found that the true issue lies with the .includes function. *经过更多测试之后,我发现真正的问题在于.includes函数。 Could anyone tell me why? 谁能告诉我为什么?

Did you mean to use getRandomNum(13) instead of getNumString(13) in your code? 您是要在代码中使用getRandomNum(13)而不是getNumString(13)吗? Your code can only generate 4 unique strings:. 您的代码只能生成4个唯一的字符串:。 .cardR01C13, .cardR02C13, .cardR03C13, .cardR03C13. .cardR01C13,.cardR02C13,.cardR03C13,.cardR03C13。 If numCards is big enough, then after generating a few cards all of these cases will be covered, yet your while loop will keep trying to generate cards as long as that card is already inside the deck (ie it keeps trying to generate unique cards). 如果numCards足够大,那么在生成了几张卡之后,所有这些情况都将被覆盖,但是只要该卡已经在套牌中,您的while循环将继续尝试生成卡(即,它一直在尝试生成唯一的卡) 。 However, there's no way it can generate any more unique cards and thus the loop will continue forever. 但是,它无法生成更多唯一的卡,因此循环将永远继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM