我如何编写一个循环,将console.log的所有数字都击中,直到它到达8的“乐透”位置;当循环运行时,它也会同时console.logs 8,但在此处停止?这是代码:
var randomNumber = Math.floor(Math.random() * 10);
function lottery() {
if (randomNumber === 8) {
return randomNumber + ": Congratulations! You won!";
} else {
return randomNumber + ": Sorry! No prize this time.";
}
};
我尝试了几次以建立一个for循环,但是它似乎并没有按照我的意愿运行。
答案 0 :(得分:0)
也许这可以帮助您吗?
function lottery(winningNumber) {
var won = false;
while (!won) {
var randomNumber = Math.floor(Math.random() * 10);
if (randomNumber == winningNumber) {
console.log(randomNumber + ": Congratulations! You won!");
won = true;
} else {
console.log(randomNumber + ": Sorry! No prize this time.");
}
}
}
lottery(8);
答案 1 :(得分:0)
您可以使用新号码再次调用函数。下面以递归方式调用彩票,为randomNumber分配一个新数字并对其进行测试。
function lottery() {
var randomNumber = Math.floor(Math.random() * 10);
if (randomNumber === 8) {
console.log(randomNumber + ": Congratulations! You won!");
return randomNumber + ": Congratulations! You won!";
} else {
console.log(randomNumber + ": Sorry! No prize this time.");
randomNumber = Math.floor(Math.random() * 10);
lottery()
return
}
}
答案 2 :(得分:-1)
您的意思是您只想连续生成一个新的随机数,直到它等于8?
let lottoFinished = false;
function lottery() {
let randomNumber = Math.floor(Math.random() * 10);
if (randomNumber === 8) {
lottoFinished = true;
return randomNumber + ": Congratulations! You won!";
} else {
return randomNumber + ": Sorry! No prize this time.";
}
}
while (!lottoFinished) {
console.log(lottery());
}
我尝试了此代码,它可以工作。