当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Uncaught TypeError: Cannot read property 'toUpperCase' of null

问题描述:

My code seems right but I don't know why I am getting this error:

Uncaught TypeError: Cannot read property 'toUpperCase' of null

Here is my code:

 //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");

}

}

the error is on the line that says if (SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') {

网友答案:

The prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel" the method returns null and your script report an error, because there is no function on null object.

Solution: check if answer isn't null, before you call toUpperCase()

if (SecondAnswer != null && SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') 
网友答案:

i think the error message is indicating the mistake of the code. This happens when SecondAnswer is null.

To avoid this error you can just include a check on top of

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

That is

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

or

if (SecondAnwser !== null && SecondAnwser.toUpperCase() === 'FEBUARY 14, 2005') {
 //
}
网友答案:

Very Strange, sometimes the java-script console says there is an error but sometimes it doesn't. Anyways, my program seems to be working correctly, so I will ignore the error. Thank you for all of you're help though (this is my first time asking a question on stackoverflow and i'm amazed by how quickly people answer my questions.)

分享给朋友:
您可能感兴趣的文章:
随机阅读: