Random Number in a do-while loop with if statement
You can do it in a more simply way:
The solution is to push
the random generated number into one array and then use join
method in order to join all elements of the array the string desired.
function getRandomNumber( upper ) {
var num = Math.floor(Math.random() * upper) + 1;
return num;
}
var array = [];
do {
random = getRandomNumber(9);
array.push(random);
} while(random != 8)
console.log(array.join(' '));
Not because it's better, but because we can (and I like generators :) ), an alternative with an iterator function (ES6 required):
function* getRandomNumbers() {
for(let num;num !==8;){
num = Math.floor((Math.random() * 9) + 1);
yield num;
}
}
let text= [...getRandomNumbers()].join(' ');
console.log(text);