parseInt()返回NaN

时间:2016-02-09 21:27:21

标签: javascript html string integer

我一直在用JavaScript学习乘法游戏here。 我的代码返回随机问题并确定给出的答案是否正确。然后,如果正确,则添加一个点并显示在屏幕上。这是问题 - 它只返回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>

2 个答案:

答案 0 :(得分:4)

基本上问题是您在执行函数后定义pointsNo变量。它还不知道 - &gt; undefined - &gt; parseInt将返回NaN

将它放在功能之前:

var pointsNo = 0;

generateNewQuestion();

var pointsStr = "Points: 0";

function generateNewQuestion() { ...

Fiddle

答案 1 :(得分:3)

您尝试将数字解析为整数以用作字符串。跳过它。

pointsStr = "Points: " + pointsNo;

你需要移动

generateNewQuestion();

初始化后的

var pointsNo = 0;
var pointsStr = "Points: 0";

声明被提升,变量被声明,但没有值,直到直接赋值。值为undefined++运算符的变量获得NaN