2016-02-09 73 views
1

我一直在为JavaScript学校的乘法游戏here工作。 我的代码返回随机问题,并确定给出的答案是否正确。然后,如果正确,则添加一个点并显示在屏幕上。这是问题 - 它只是返回NaN。每次答案正确时,积分都会增加。我使用parseInt()将该数字添加到字符串中,并将其与字符Points:并排显示,但不是显示Points: 1,而是显示Points: NaNparseInt()返回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> 
+0

无关的问题,但在你的if语句,你可以检查,如果'回答== userAnswer'而不是再次加 –

+0

@NuclearGhost我看到。我在补充说,当我意识到点没有添加,所以我停了下来。谢谢你提醒我! ;) –

回答

5

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

将它的函数之前:

var pointsNo = 0; 

generateNewQuestion(); 

var pointsStr = "Points: 0"; 

function generateNewQuestion() { ... 

Fiddle

+0

感谢您的回复。我明天会尝试。我有GMT±0,所以我很累... –

3

您尝试解析数整数用作字符串。只需跳过它。

pointsStr = "Points: " + pointsNo; 

,你需要声明悬挂,变量被宣布

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

初始化后移动

generateNewQuestion(); 

,但没有值,直到该值是直接分配。具有值undefined++运算符的变量获得NaN

+2

这应该不是错误? – daniel

+0

@丹尼尔,对,这是另一个错误。 –