【问题标题】:parseInt() returns NaNparseInt() 返回 NaN
【发布时间】:2016-05-20 01:19:54
【问题描述】:

我一直在用 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>

【问题讨论】:

  • 与问题无关,但在你的if语句中,你可以检查answer == userAnswer而不是再次添加
  • @NuclearGhost 我明白了。当我意识到积分没有增加时,我正在添加它,所以我停了下来。谢谢你提醒我! ;)

标签: javascript html string integer


【解决方案1】:

基本上问题是您在执行函数后定义了pointsNo 变量。目前还不知道 -> 未定义 -> parseInt 将返回 NaN

把它放在函数之前:

var pointsNo = 0;

generateNewQuestion();

var pointsStr = "Points: 0";

function generateNewQuestion() { ...

Fiddle

【讨论】:

  • 感谢您的回复。我明天试试。我有 GMT±0,所以我很累......
【解决方案2】:

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

pointsStr = "Points: " + pointsNo;

你需要移动

generateNewQuestion();

初始化后

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

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

【讨论】:

    猜你喜欢
    • 2012-04-28
    • 2014-11-16
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 2016-01-14
    相关资源
    最近更新 更多