2016-08-24 56 views
-3
的特性“toUpperCase”

我的代码似乎是正确的,但我不知道为什么我收到此错误:遗漏的类型错误:无法读取空

Uncaught TypeError: Cannot read property 'toUpperCase' of null

这里是我的代码:

//The function is executed after someone clicks the "Take the Quiz" 
    function startquiz() { 
     //The variable for the first question 
     var FirstAnwser = prompt("Who posted the first youtube video?"); 
     //The if statement for the first question 
     if (FirstAnwser.toUpperCase() === 'JAWED KARIM') { 
      //If the person is correct a dialog box that says correct pops up 
      alert("Correct"); 
      //The Variable for the second question 
      var SecondAnwser = prompt("When was the domain name youtube.com  activated?"); 
      if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') { 
       alert("Correct"); 
       var ThirdAnwser = prompt("What was the first video on youtube called?"); 
       if (ThirdAnwser.toUpperCase() === 'ME AT THE ZOO') { 
        alert("Correct"); 
       } else { 
        alert("Sorry, That is Wrong"); 
       } 

      } else { 
       alert("Sorry, That is Wrong"); 
      } 
     } else { 
      //If the person is wrong a dialog box pops up which says "Sorry, That is wrong" 
      alert("Sorry, That is Wrong"); 
     } 
    } 

错误发生在if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') {

+1

第一个迂腐的东西:单词拼写为“answer” – Pointy

+2

和'FEBUARY'拼错了 – epascarello

+0

并且为了让它失效,我无法重现这个问题:https://jsfiddle.net/jt319dj0/。如果我想点击'取消'会有帮助。 –

回答

4

如果用户单击“确定”,prompt()方法将返回输入值。如果用户单击“取消”,则该方法返回null,并且您的脚本会报告错误,因为null对象上没有功能。

解决方法:检查答案是不为空,你叫toUpperCase()

if (SecondAnswer != null && SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') 
1

之前,我认为错误消息显示代码错误。当SecondAnswer为空时会发生这种情况。

为了避免这种错误,你可以只包括对

if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') 

顶部的检查是

if (SecondAnwser !== null) { 
    if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') { 
    // 
    } 
} 

if (SecondAnwser !== null && SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') { 
// 
} 
0

很奇怪,有时Java的脚本控制台说有一个错误,但有时它不会。无论如何,我的程序似乎工作正常,所以我会忽略错误。谢谢你们所有人的帮助,虽然(这是我第一次问stackoverflow的问题,我很惊讶人们回答我的问题的速度有多快。)

相关问题