我一直在为JavaScript的学校做一个乘法游戏JavaScript。我的代码返回随机问题,并确定所给出的答案是否正确。然后,如果正确的话,添加一个点并显示在屏幕上。这就是问题所在--它只返回NaN。每次答案正确时的积分增量。我使用parseInt()将数字添加到字符串中,并将其与字符Points:一起显示,但它不是显示Points: 1,而是显示Points: NaN。
<body>
<p id="pts" style="text-align: right;">
<script>
generateNewQuestion();
var pointsNo = 0;
var pointsStr = "Points: 0";
function generateNewQuestion() {
var num1 = Math.floor((Math.random() * 100) + 1);
var num2 = Math.floor((Math.random() * 100) + 1);
var answer = num1+num2;
var userAnswer = prompt("What is: " + num1 + " + " + num2 + "?");
if (num1+num2==userAnswer) {
// increments the points by 1
pointsNo++;
pointsStr = "Points: " + parseInt(pointsNo);
// shows points on user's screen
document.getElementById("pts").innerHTML = pointsStr;
// ask if the user wishes to do another question
var anotherQuestion = alert("Correct! You earn one point! Do another?");
// give another if requested
if (anotherQuestion == true) {
generateNewQuestion();
} else {
alert("You're just not good enough..\n I get it... Your points are on the top right!")
}
} else {
alert("Sorry, that was the wrong answer.\nThe correct answer was " + answer + ". Try another!");
generateNewQuestion();
}
}
</script>
</body>发布于 2016-02-09 21:33:48
基本上,问题是在执行函数之后定义了pointsNo变量。还不知道->未定义的-> parseInt将返回NaN。
把它放在功能之前:
var pointsNo = 0;
generateNewQuestion();
var pointsStr = "Points: 0";
function generateNewQuestion() { ...发布于 2016-02-09 21:30:07
您尝试将数字解析为整数,以便用作字符串。跳过去就行了。
pointsStr = "Points: " + pointsNo;你得搬家
generateNewQuestion();初始化后,
var pointsNo = 0;
var pointsStr = "Points: 0";声明被悬挂,变量被声明,但没有值,直到该值被直接赋值。具有值undefined和++运算符的变量将获得NaN。
https://stackoverflow.com/questions/35302507
复制相似问题