do while javascript - 猜谜游戏的循环
Posted
技术标签:
【中文标题】do while javascript - 猜谜游戏的循环【英文标题】:do while javascript - loop for guessing game 【发布时间】:2015-10-22 20:14:40 【问题描述】:<!DOCTYPE html PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title>Game</title>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<h1>GameSite</h1>
<p> This program will generate a random number. Please input your guess in the box!</p>
<button onclick="guessGame()">Press me to play a quick game!</button>
<script>
function guessGame()
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
do
guess = prompt("Keep guessing!");
if (number < guess)
prompt("You've guessed too high!");
else if (number > guess)
prompt("You've guessed too low!");
else document.write("Good Job!");
while (guess != number);
</script>
</body>
</html>
我遇到了循环问题。它循环正常,但如果我在 if 语句之后也移动了guess 语句,它每次都会回到那个状态。如果我把它放在 if 语句之外,那么它似乎实际上不允许我猜测一个有效的数字。很难解释:\
【问题讨论】:
【参考方案1】:试试这个:
function guessGame()
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
while (guess != number)
if (number < guess)
guess = prompt("You've guessed too high! Keep guessing!");
else
guess = prompt("You've guessed too low! Keep guessing!");
document.write("Good Job!");
while 循环会一直运行,直到猜到正确的数字,然后才会终止。
编辑:抱歉,打字太快会出错
【讨论】:
!==
运算符对你来说真是个下流的玩笑:由于提示结果是字符串,而数字是整数,所以用户将注定永远猜不透。
哦,感谢 Jan 的更正,我已经习惯了总是使用 !== 以至于我对此感到震惊。
为什么要删除它?我会保留它,所以游戏会更有趣>:-D【参考方案2】:
我建议只使用一个提示并将其分配给变量。
function guessGame()
var number = Math.random() * 11 | 0,
guess,
text = 'Guess a number:';
do
guess = prompt(text);
if (number < guess)
text = "You've guessed too high!";
else if (number > guess)
text = "You've guessed too low!";
while (guess != number);
document.write("Good Job!");
guessGame();
【讨论】:
但是当你按下按钮时会出现正确的数字。 @AltayMazlum,这种行为在原始代码中也是如此。 我知道但你回答却不解决,为什么? @AltayMazlum,这样更好吗? 好的,谢谢。我问是因为我也想知道它是如何完成的。【参考方案3】:当您不需要用户回复时,我建议您使用alert
function guessGame()
number = Math.floor(Math.random()*11);
var guess;
do
guess = prompt("Guess a number: "); // you should handle string input here
if (number < guess)
alert("You've guessed too high!");
alert("Keep guessing!");
else if (number > guess)
alert("You've guessed too low!");
alert("Keep guessing!");
while (guess != number);
alert("Good Job!");
【讨论】:
谢谢!我最终使用警报来跟随弹出框的样式!【参考方案4】:相信我,我是一名程序员。
function guessGame()
guess:
var number = Math.floor(Math.random() * 11);
document.write(number);
var guess;// = prompt("Guess a number: ");
var text = 'Guess a number:';
guess = prompt(text);
if (number == guess)
document.write("Good Job!");
return true;
else
if (number < guess)
text = "You've guessed too low!";
else
text = "You've guessed too high!";
goto guess;
guessGame();
【讨论】:
这个答案是错误的。从语法错误到goto
.
在JS中使用goto是not that easy,但另一方面我们必须摆脱goto仇恨的社会潮流。以上是关于do while javascript - 猜谜游戏的循环的主要内容,如果未能解决你的问题,请参考以下文章
专题讲解:JavaScript中while以及do while循环
JavaScript循环 while/do while/for的使用