幸运奖品游戏无限循环?

时间:2017-11-29 17:34:39

标签: javascript loops

我做了一个基本的幸运奖'在Javascript游戏,但无法解决如何阻止它无限循环。有什么我明显做错了,因为我是一个初学者,我们将不胜感激。

var winNumber = 0;
var lossNumber = 0;

while (lossNumber < 10);
{
    var randomNumber = Math.floor(Math.random() * 100);
    if (randomNumber > 20 && randomNumber < 40) {
        var winNumber = winNumber + 1;
    } else
    {
        var lossNumber = lossNumber + 1;
    }
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);

非常感谢

2 个答案:

答案 0 :(得分:1)

您重新声明了变量winNumberlossNumber

试试这个:

var winNumber = 0;
var lossNumber = 0;

while (lossNumber < 10)
{
    var randomNumber = Math.floor(Math.random() * 100);
    if (randomNumber > 20 && randomNumber < 40) {
        winNumber = winNumber + 1;
    } 
    else {
        lossNumber = lossNumber + 1;
    }
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);

答案 1 :(得分:1)

实际上,您的整个问题都归因于while (lossNumber < 10);

中的错误分号

这会导致其余的条件不被评估,因此循环永远不会结束。在循环中再次使用var是不必要的,但它也不是问题的原因,分号是。

&#13;
&#13;
var winNumber = 0;
var lossNumber = 0;

while (lossNumber < 10)
{
    var randomNumber = Math.floor(Math.random() * 100);
    if (randomNumber > 20 && randomNumber < 40) {
        var winNumber = winNumber + 1;
    } else
    {
        var lossNumber = lossNumber + 1;
    }
}
console.log('Number of wins: ' + winNumber);
console.log('Number of losses: ' + lossNumber);
&#13;
&#13;
&#13;