I've made a JavaScript 'while' loop to keep adding a random number from 1 to 10 to an array until the random number is 9 or 10.
function random() {
return Math.floor(Math.random() * (10)) + 1;
}
var array = [];
var element = 0;
while (element < 9) {
element = random();
if (element < 9) {
array.push(element);
}
}
console.log(array);
I have two questions.
How can I make the 'while' loop more elegant - without using (element < 9) two times?
How can I do this in a more elegant way, without using a 'while' loop?
whileloop because you're doing something while a condition is true. Trywhile( (element = random()) < 9) array.push(element);.random()and the.push, initializingelementasrandom()instead of0. EDIT: Seems cᴏʟᴅsᴘᴇᴇᴅ suggested the same thing as me, though Niet's answer is likely best.