我做了一个基本的幸运奖'在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);
非常感谢
答案 0 :(得分:1)
您重新声明了变量winNumber
和lossNumber
。
试试这个:
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
是不必要的,但它也不是问题的原因,分号是。
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;