Below you can find the code for creating random 8 numbers between 1 and 80. It puts the random numbers into the numbers array and writes into the divs. Code runs without any problem if it increments the x inside if brackets. If I put the 'x++' outside of if brackets, after several run I found that sometimes it creates a same random number and finds inside the numbers array. Then it skips and that div comes empty.
What is the difference between incrementing x in if block and incrementing 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>