我正在制作一个基于浏览器的数学游戏,并且遇到了循环错误。
数字在0到20之间生成,如果它们的和或差(在适用时)落在0或20之外,则会再次生成。
function mathFunction() {
//generates a value of 0 or 1 to dermine if the problem will be addition or subtraction (0 = + , 1 = -)
var sign = Math.floor(Math.random() * 2);
if (sign == 0) {
dsign = " + ";
} else {
dsign = " - ";
}
//generates two random values between 0 and 20
var num1 = Math.floor(Math.random() * 21);
var num2 = Math.floor(Math.random() * 21);
//if the sum of an addition problem is greater than 20, it calls mathFunction to make new values
if (sign == 0) {
if (num1 + num2 > 20) {
mathFunction();
}
//if the difference of a subtraction problem is less than 0, it calls mathFunction to make new values
} if (sign == 1) {
if (num1 - num2 < 0) {
mathFunction();
}
}
变量将发送到评估函数。
//evalFunction is called when the button is clicked, and passes the 2 numbers and the sign value
document.getElementById("enterButton").addEventListener('mousedown', function() {
evalFunction(num1, num2, sign);
}, false);
}
function evalFunction(num1, num2, sign) {
var counter = 1;
alert("fire");
var answer = document.getElementById("answer").value;
我添加了警报以帮助跟踪事件。 第一次按Enter将导致正常结果。 在第一个问题出现后按Enter键将导致错误,这些错误似乎是函数循环的结果。
//calls mathFunction to generate a new question
alert(counter + " num 1: " + num1);
alert(counter + " num 2: " + num2);
alert(counter + " answer: " + answer);
counter = counter + 1;
mathFunction();
}
//loads first question
window.onload = mathFunction();
我已将整个代码粘贴到pastebin中。预先感谢您的任何建议。
答案 0 :(得分:0)
循环错误是由于mathFunction()
无效而导致的。
所以调用堆栈看起来像这样:
mathFunction() --> mathFunction() --> mathFunction()
当堆栈顶部的mathFunction完成时,下一个mathFunction()
继续执行,好像什么都没发生。
请尝试使用一个将数学问题作为对象返回的函数,而不要使用mathFunction()
:
function generateProblem() {
//generates a value of 0 or 1 to dermine if the problem will be addition or subtraction (0 = + , 1 = -)
var sign = Math.floor(Math.random() * 2);
if (sign == 0) {
dsign = " + ";
} else {
dsign = " - ";
}
//generates two random values between 0 and 20
var num1 = Math.floor(Math.random() * 21);
var num2 = Math.floor(Math.random() * 21);
//return the problem as an object
return {sign: dsign, first: num1, second: num2};
}
然后将这个问题生成器函数循环放置:
var problem;
while (true) {
problem = generateProblem();
//checks for addition, you can expand it to check for valid subtraction questions as well
if (problem.sign == " + ") {
if (problem.first + problem.second == 20) {
continue; //this problem isn't valid, so restart at the top of the loop
}
}
}
总而言之,mathFunction()有时会自行调用。发生这种情况时,结果就是功能堆积了。为避免这种情况,请将问题生成放在函数中,然后将问题检查放入循环中。这样,调用堆栈就不会与mathFunction()堆积在一起。