While循环在JS函数中不起作用
While loop doesn't work inside a function JS
我使用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();
};
}
相关文章:
- 监视函数从服务返回不起作用,但作用域函数起作用
- Ember Data DS.Model's set函数不起作用
- Javascript:If-then语句在函数中不起作用
- JavaScript链接在点击时不起作用;函数在页面加载时工作
- AngularJS指令部分应用的函数don'不起作用
- 为什么我的JavaScript堆栈排序函数不起作用
- 嵌套到另一个函数中的Fancybox函数;不起作用
- Javascript onchange()函数不起作用
- I'我试图在文本区域中进行特定的输入,调用特定的javascript函数,但没有成功;不起作用
- javascript函数调用不起作用
- 另一个Ajax函数触发的Ajax函数不起作用
- 从PHP调用JS函数不起作用
- 清除函数中if语句内部不起作用的间隔
- js函数堆栈传入变量,.hide()不起作用
- jQuery validate函数不起作用
- jQuery克隆函数在chrome中不起作用
- JS-窗口宽度函数不起作用
- 函数调用不起作用
- .hasClass 在 onclick 函数中不起作用,但删除和添加类函数可以
- javascript函数,该函数不起作用,但不会显示任何错误