parseInt() returns NaN

parseInt() returns NaN

本文关键字:NaN returns parseInt      更新时间:2023-09-26

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