parseInt() returns NaN
parseInt() returns NaN
我一直在用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>
基本上问题是你在执行函数后定义了pointsNo
变量。目前还不知道 ->未定义 -> parseInt
将返回NaN
.
将其放在函数之前:
var pointsNo = 0;
generateNewQuestion();
var pointsStr = "Points: 0";
function generateNewQuestion() { ...
小提琴
您尝试将数字解析为整数以用作字符串。跳过它。
pointsStr = "Points: " + pointsNo;
你需要移动
generateNewQuestion();
初始化后
var pointsNo = 0;
var pointsStr = "Points: 0";
声明被提升,变量被声明,但没有值,直到直接赋值。值为 undefined
且带有 ++
运算符的变量将获得NaN
。
相关文章:
- JavaScript NaN equvialence
- 如何为排除无穷大和NaN的数字声明Flow类型
- 为什么我在这个javaScript代码中使用NaN
- 如何防止Math.max()返回NaN
- 函数将输出nan而不是数字,为什么
- jquery中出现NaN错误.已经尝试过ParseInt,但仍然不起作用
- 尝试求和时,在我的表的页脚中返回$NaN
- 我的jquery中出现NaN错误
- parseInt("08") returns 0
- 金额结果为NaN
- 使用running total时使用Javascript$NaN
- 使用jquery CounterUp提供NaN的百万值
- Javascript Timer returns NaN
- moment .toJSON returns "0NaN-NaN-NaNTNaN:NaN:NaN.NaNZ&q
- parseInt() returns NaN
- parseInt returns NaN
- Facebook FQL returns NaN value
- d3.scale.linear() returns NaN
- JavaScript Total Returns NaN
- jQuery UI $.datepicker.formatDate returns NaN NaN Nan