首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >parseInt()返回NaN

parseInt()返回NaN
EN

Stack Overflow用户
提问于 2016-02-09 21:27:20
回答 2查看 979关注 0票数 1

我一直在为JavaScript的学校做一个乘法游戏JavaScript。我的代码返回随机问题,并确定所给出的答案是否正确。然后,如果正确的话,添加一个点并显示在屏幕上。这就是问题所在--它只返回NaN。每次答案正确时的积分增量。我使用parseInt()将数字添加到字符串中,并将其与字符Points:一起显示,但它不是显示Points: 1,而是显示Points: NaN

代码语言:javascript
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-09 21:33:48

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

把它放在功能之前:

代码语言:javascript
复制
var pointsNo = 0;

generateNewQuestion();

var pointsStr = "Points: 0";

function generateNewQuestion() { ...

小提琴

票数 4
EN

Stack Overflow用户

发布于 2016-02-09 21:30:07

您尝试将数字解析为整数,以便用作字符串。跳过去就行了。

代码语言:javascript
复制
pointsStr = "Points: " + pointsNo;

你得搬家

代码语言:javascript
复制
generateNewQuestion();

初始化后,

代码语言:javascript
复制
var pointsNo = 0;
var pointsStr = "Points: 0";

声明被悬挂,变量被声明,但没有值,直到该值被直接赋值。具有值undefined++运算符的变量将获得NaN

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35302507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档