gpt4 book ai didi

Javascript - 子函数中的 boolean 全局变量不改变

转载 作者:行者123 更新时间:2023-12-03 12:13:00 25 4
gpt4 key购买 nike

我正在开发一个学生项目:一个“热或冷”的游戏应用程序,但似乎无法理解某些东西。

  1. 这是该项目的链接:用户应该在文本框中输入数字,尝试猜测随机生成的数字。当他猜对时——游戏结束。 https://dl.dropboxusercontent.com/u/33890425/Thinkful/hot-or-cold-starter/index.html

问题是,当有正确的猜测时,我设置的用于注册猜测的标志不会永久注册更改(由正确的猜测引起),并且用户可以继续猜测。

当用户做出正确的猜测时,我会更改全局变量 winflag 的值,但由于某种原因,它会返回 false(即尚未猜测)并继续游戏。

谁能指出为什么会发生这种情况?

//INSIDE DOCUMENT.READY

//global variable declaration
var winflag=false;

//event handler for click on guess button
$('#guessButton').click(function(){
event.preventDefault();
if(!winflag) {
console.log("calling guessfunction")
guessfunction();
}
else {
alert("Game is over");
}
});
//END OF DOCUMENT READY

var guessfunction = function () {
//guesscount++ -- write guesscount in #count
guesscount++;
console.log("guesscount is " + guesscount);
//current guess cguess=get the input from the text box
var tcguess = $('#userGuess').val();
var cguess = +tcguess;
//if cguess>100 - alert "not valid input"
if (cguess>100) {
return alert("Not a valid input");
}
else {
//append cguess in #guessList
$('#guessList').append('<li>'+tcguess+'</li>');
//calculatefeedback(solution,cguess)
calculatefeedback(solution,cguess);
console.log("calculated feedback");
}}

var calculatefeedback = function(sol,guess) {
//difference=absolute value(solution-guess)
var difference = Math.abs(solution-guess);
//if difference=>70 --- return you're freezing
if (difference >= 70) {
winflag=false;
return alert("You're freezing!");
}
//else if difference=>30 --- return youre cold
else if (difference >= 30) {
winflag=false;
return alert("You're cold!");
}
//else if difference=>15 --- return youre warm
else if (difference >= 15) {
winflag=false;
return alert("You're warm!");
}
//else if difference=>5 --- return hot
else if (difference >= 5) {
winflag=false;
return alert("You're hot!");
}
//else if difference>=1 --- return burning
else if (difference >= 1) {
winflag=false;
return alert("You're burning!");
}
//else if difference=0 --- return GUESSED
else if (difference == 0) {
winflag=true;
return alert("You guessed!");
}
//else alert "not valid input"
else {
return alert("Not a valid input");
}
//end game
}

最佳答案

如果您在 $(document).ready(function() {}) 中设置 var winflag=false; 那么它不会在全局上设置范围。 winflag 正在文档就绪的范围内设置。您需要像这样设置window.winflag=false

关于Javascript - 子函数中的 boolean 全局变量不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com