2016-08-24 106 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的問題,我很驚訝人們回答我的問題的速度有多快。)

相關問題