简体   繁体   中英

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. 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). 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. Could anyone tell me why?

Did you mean to use getRandomNum(13) instead of getNumString(13) in your code? Your code can only generate 4 unique strings:. .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). However, there's no way it can generate any more unique cards and thus the loop will continue forever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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