Below you can find the code for creating random 8 numbers from 1 to 80. It puts random numbers into an array of numbers and writes them in a div. The code works without any problems if it increments x inside, if parentheses. If I put βx ++β outside the brackets, after several runs, I found that sometimes it creates the same random number and finds it inside the array of numbers. Then it skips and that div is empty.
What is the difference between increment x in if block and increment x outside if block?
Inside the if block:
var numbers = []
var luckyNumber;
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
x++;
}
}
Outside the if block:
var numbers = []
var luckyNumber;
var x = 1;
while (x <= 8) {
luckyNumber = Math.floor(Math.random() * 80 + 1);
if (numbers.indexOf(luckyNumber) == -1) {
document.getElementById('k' + x).innerHTML = luckyNumber;
numbers.push(luckyNumber);
}
x++;
}
HTML:
<div id="k1">K1</div>
<div id="k2">K2</div>
<div id="k3">K3</div>
<div id="k4">K4</div>
<div id="k5">K5</div>
<div id="k6">K6</div>
<div id="k7">K7</div>
<div id="k8">K8</div>
user7580495
source
share