未捕获的TypeError:无法读取属性' toUpperCase'为null

时间:2016-08-24 01:17:54

标签: javascript

我的代码似乎没错,但我不知道为什么会收到此错误:

  

未捕获的TypeError:无法读取属性' toUpperCase'为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') {

3 个答案:

答案 0 :(得分:4)

如果用户点击" OK"则prompt()方法返回输入值。如果用户点击"取消"该方法返回null,并且您的脚本报告错误,因为null对象上没有函数。

解决方案:在致电toUpperCase()

之前,请检查答案是否为空
if (SecondAnswer != null && SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') 

答案 1 :(得分:1)

我认为错误消息表明代码有误。当SecondAnswer为null时会发生这种情况。

要避免此错误,您只需在

上添加支票即可
if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') 

那是

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

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

答案 2 :(得分:0)

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