我一直在为JavaScript学校的乘法游戏here工作。 我的代码返回随机问题,并确定给出的答案是否正确。然后,如果正确,则添加一个点并显示在屏幕上。这是问题 - 它只是返回NaN。每次答案正确时,积分都会增加。我使用parseInt()
将该数字添加到字符串中,并将其与字符Points:
并排显示,但不是显示Points: 1
,而是显示Points: NaN
。parseInt()返回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>
无关的问题,但在你的if语句,你可以检查,如果'回答== userAnswer'而不是再次加 –
@NuclearGhost我看到。我在补充说,当我意识到点没有添加,所以我停了下来。谢谢你提醒我! ;) –