我想了解为什么数组randomNumber中的随机数不重复。我已经执行了50x的代码,数组中的数字再也不会重复了。我真的很高兴他们不重复,但想了解为什么他们不重复?还是他们没有重复我的fl幸,我应该很快看到重复吗?



var numberOptions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var randomNumbers = [];


while (randomNumbers.length < 4) {
  var randomnumber = Math.floor(Math.random() * numberOptions.length + 1);
  if (randomNumbers.indexOf(randomnumber) > -1) continue;
  randomNumbers[randomNumbers.length] = randomnumber;
}

var html =
  "<p>My 1st number: " + randomNumbers[0] + "</p>" +
  "<p>My 2nd number: " + randomNumbers[1] + "</p>" +
  "<p>My 3rd number: " + randomNumbers[2] + "</p>" +
  "<p>My 4th number: " + randomNumbers[3] + "</p>";
document.querySelector("#number").innerHTML = html;

<div id="number">
</div>

最佳答案

该代码明确避免重复:

while (randomNumbers.length < 4) { //until there are four random numbers, repeat:
  //generate a random number
  var randomnumber = Math.floor(Math.random() * numberOptions.length + 1);
  //if the number is already in the array, go back to the beginning of the loop
  if (randomNumbers.indexOf(randomnumber) > -1) continue;
  //if the number is new, add it to the array
  randomNumbers[randomNumbers.length] = randomnumber;
}

09-29 20:24