While循环在JS函数中不起作用

While loop doesn't work inside a function JS

本文关键字:不起作用 函数 JS 循环 While      更新时间:2023-09-26

我使用javascript构建了一个颜色猜谜游戏。在do_game函数内部的情况下,循环不起作用。如果我把它放在do_game之外,它就会工作,但只有check_guess中的第一个If对所有选项都有效。请帮我解决这个问题

    var chosen;
var userInputText;
var finished = false;
var guesses = 0;
var colors = ["aqua", "azure", "beige", "brown", "chocolate", "coral", "crismon", "gold", "lime", "linen", "snow", "tomato"];
/*  
  One way to set the background color of a web page is
  myBody=document.getElementsByTagName("body")[0];
  myBody.style.background=name_of_color;*/
function do_game() {
    "use strict";
    chosen = colors[Math.floor(Math.random() * colors.length)];
    while(!finished) {
        userInputText = prompt("I am thinking of one of these colors: 'n'n aqua, azure, beige, brown, chocolate, coral, crismon, gold, lime, linen, snow, tomato'n'nWhat color am I thinking of?");
        guesses += 1;
        finished = check_guess();
    };
}
function check_guess() {
    "use strict";
    var idx = colors.indexOf(userInputText);
    if(idx === -1) {
        alert("Sorry, I don't recognize your color'n'n" + "Please try again.");
        return false;
    }
    if(userInputText > chosen) {
        alert("Sorry, your guess is not correct!'n'n" + "Hint: your color is alphabitcally higher than mine.'n'n" + "Please try again.");
        return false;
    }
    if(userInputText < chosen) {
        alert("Sorry, your guess is not correct!'n'n" + "Hint: your color is alphabitcally lower than mine.'n'n" + "Please try again.'n'n");
        return false;
    }if (userInputText === chosen) {
        alert("Congratulations! You have guesses the color!" + "It took you " + guesses + " to finish the game!" + "You can see the colour in the background");
        return true;
    }

}

此处未更新猜测值

guesses = +1;

替换
guesses += 1

guesses++

这里的问题是全局完成变量。一旦check_guess()在调用一次后将其设置为true,它将阻止循环在以后运行。只需将其放入do_game()函数中。

function do_game() {
    "use strict";
    var finished = false;
    chosen = colors[Math.floor(Math.random() * colors.length)];
    while(!finished) {
        userInputText = prompt("I am thinking of one of these colors: 'n'n aqua, azure, beige, brown, chocolate, coral, crismon, gold, lime, linen, snow, tomato'n'nWhat color am I thinking of?");
        guesses += 1;
        finished = check_guess();
    };
}