如果在猜对了之后如何停止循环?
<!DOCTYPE html>
<html>
<body onLoad = "do_game()">
<script>
var target;
var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"].sort();
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
//main function
function do_game() {
var random_color = color[Math.floor(Math.random() * color.length)]; // Get a Random value from array
target = random_color;
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors:- \n\n" +
color.join(", ") +
".\n\nWhat color am I thinking of?");
guess_input = guess_input_text;
guesses += 1;
if( guess_input === target){
alert("Your Guess is Right.Congratulations!");//finish which causing problem
}
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
如果我没有误解你的问题,你想在警告猜测正确后停止它。
您的循环正在检查finished
是否为真,因此如果finished
仍为假,您的循环将不会停止。
解决方案是将finished
设置为true
。以下代码应该有效:
function do_game() {
var random_color = color[Math.floor(Math.random() * color.length)]; // Get a Random value from array
target = random_color;
while (!finished)
{
guess_input_text = prompt("I am thinking of one of these colors:- \n\n" +
color.join(", ") +
".\n\nWhat color am I thinking of?");
guess_input = guess_input_text;
guesses += 1;
if( guess_input === target)
{
alert("Your Guess is Right.Congratulations!");
finished = true;
// You can also use break statement to
// make sure that the loop will stop.
}
}
}