2013-08-16 103 views
0

在udemy上使用JavaScript進行在線課程。嘗試編碼我學到的東西。我收到一個未定義的錯誤。 Visual Studio 2012 Pro說代碼是找到的,但是當我運行代碼時,我得到錯誤。VS中的JavaScript未定義錯誤

 <script type="text/javascript"> 
     var numericalGrade = 82; 
     var letterGrade; 
     function myResaults() { 
      document.write("Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />"); 
     } 

     if (numericalGrade >= 90) { 
      letterGrade = "A"; 
      document.write(myResaults() + " Excellent, you passed this course with flying colors..."); 
     } 

     else if (numericalGrade >= 80) { 
      letterGrade = "B"; 
      document.write(myResaults() + " Excellent, you passed this course with a great grade.."); 

     } 
     else if (numericalGrade >= 70) { 
      letterGrade = "C"; 
      document.write(myResaults() + " Congratulations, you passed this course..."); 

     } 
     else if (numericalGrade >= 60) { 
      letterGrade = "D"; 
      document.write(myResaults() + " You revived a grade that will not permit you to pass this course. You can retake this course at a later date."); 

     } 
     else { 
      letterGrade = "F"; 
      document.write(myResaults() + "You failed this course. You can retake this course at a later date."); 

     } 
    </script> 

那麼我做錯了什麼。我對JavaScript編碼非常陌生。

+2

什麼是確切的錯誤? – j08691

+2

'myResaults()'返回'undefined',因爲它沒有'return'語句。當你執行'myResaults()+「」'時,你將'undefined'連接到一個字符串,所以你看到'undefined'。 –

回答

3

你的函數需要返回一個值,但因爲它不是你得到的未定義。

變化:

function myResaults() { 
    document.write("Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />"); 
} 

function myResaults() { 
    return "Your score is " + numericalGrade + "%. Your grade will be a " + letterGrade + ".<br />"; 
} 
+0

謝謝,它的工作。我不知道退貨是什麼。也許在課程視頻中,教練將解釋什麼是回報。再次感謝。 –

+0

返回做的非常多,指定一個值返回給所謂的函數。請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return。正如MDN文檔所示,「要返回的表達式,如果省略,則返回undefined。」 – j08691