如何让javascript提示一个问题一组次数



我试图写一个简单的程序,让用户猜一个随机数一组次数。到目前为止,我有以下内容:

<!DOCTYPE html>
<html>
<head>
<title>Decisions and Loops</title>
</head>
<body>
</body>
<script>
var rNum = Math.ceil(Math.random() * 30);
var myInput = Number (prompt ("Please enter your Guess: "));

if (myInput == rNum) {
alert("Good guess");
} 
else if (myInput >= rNum){
alert((prompt ("Sorry, guess if too low, try again"));
} 
else {
alert((prompt ("Sorry, guess if too high, try again"));
}
</script>
</html>

两个问题1.由于某种原因,这不起作用。2.如何让程序多次迭代循环?如有任何协助,我们将不胜感激。

var rNum = Math.ceil(Math.random() * 30);
var myInput;
var numTimesToAsk = 3;
for (var i = 0; i < numTimesToAsk; i++) {
myInput = Number (prompt ("Please enter your Guess: "));
if(myInput === rNum) {
alert("Good guess");
break; //if you want the loop to stop here since they guessed correctly
} else if (myInput >= rNum) {
alert("Sorry, guess is too low, try again");
} else {
alert("Sorry, guess is too high, try again");
}
}

一个几乎没有逻辑修复的基本实现可能是这样的:

// To limit the number of prompts, or else loop might go on forever
var max_try = 5;
function ShowQuiz() {
var rNum = Math.ceil(Math.random() * 30);
var myInput = Number(prompt("Please enter your Guess: "));
if (myInput == rNum) {
alert("Good guess");
} else if (myInput < rNum) {
alert("Sorry, your guess is too low, try again");
if (--max_try > 0) ShowQuiz()
} else {
alert("Sorry, your guess is too high, try again");
if (--max_try > 0) ShowQuiz()
}
}
ShowQuiz();

相关内容

最新更新