JavaScript中循环函数的原因



https://pastebin.com/fZsTQLTP

我正在制作一个基于浏览器的数学游戏,遇到了一个循环错误。

这些数字在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键将导致错误,这些错误似乎是函数循环的结果。

//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中。提前谢谢你的建议。

循环错误是由于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((。

最新更新