2017-01-03 100 views
1

我必須按照視頻中的說明製作測驗應用程序。我遵循指示並製作應用程序。幾乎一切正常,但在測驗結束時我沒有得分。 Web控制檯顯示的代碼(用粗體字16行)的以下部分類型錯誤:TypeError:q未定義(在JS中)

var currentQuestion = 0; 
var score = 0; 
var totQuestions = questions.length; 

var container = document.getElementById('quizContainer'); 
var questionEl = document.getElementById('question'); 
var opt1 = document.getElementById('opt1'); 
var opt2 = document.getElementById('opt2'); 
var opt3 = document.getElementById('opt3'); 
var opt4 = document.getElementById('opt4'); 
var nextButton = document.getElementById('nextButton'); 
var resultCont = document.getElementById('result'); 

function loadQuestion (questionIndex) { 
var q = questions[questionIndex]; 
**questionEl.textContent = (questionIndex + 1) + '. ' + q.question;** 
opt1.textContent = q.option1; 
opt2.textContent = q.option2; 
opt3.textContent = q.option3; 
opt4.textContent = q.option4; 

}; 
function loadNextQuestion() { 
var selectedOption = document.querySelector('input[type=radio]:checked'); 
if(!selectedOption){ 
    alert('Please select your answer!'); 
    return; 
} 
var answer = selectedOption.value; 
if(questions[currentQuestion].answer ==answer){ 
    score += 10; 
} 
selectedOption.checked = false; 
currentQuestion++; 
if(currentQuestion == totQuestions - 1){ 
    nextButton.textContent = 'Finish'; 
} 
if(currentQuestion == totQuestions){ 
    container.style.display = 'none'; 
    resultCont.style.display = ''; 
    resultCont.textContent = 'Your score: ' + score; 
} 
loadQuestion(currentQuestion); 
} 
loadQuestion(currentQuestion); 

任何人都可以請指出錯誤? 這裏是其中問題定義的文件:

var questions = [{ 
"question": "Why do we use the present simple tense?", 
"option1": "General truths and facts", 
"option2": "Complete action", 
"option3": "Continuous action", 
"option4": "Continuous action linked with past", 
"answer": "1" 
}, { 
"question": "Why do we use the present continuous tense?", 
"option1": "General truths and facts", 
"option2": "Complete action", 
"option3": "Continuous action", 
"option4": "Continuous action linked with past", 
"answer": "3" 
}, { 
"question": "Why do we use the present perfect tense?", 
"option1": "General truths and facts", 
"option2": "Complete action", 
"option3": "Continuous action", 
"option4": "Continuous action linked with past", 
"answer": "2" 
}, { 
"question": "Why do we use the present perfect continuous tense?", 
"option1": "General truths and facts", 
"option2": "Complete action", 
"option3": "Continuous action", 
"option4": "Continuous action linked with past", 
"answer": "4" 
}] 
+0

什麼是「問題」,它來自哪裏? – Craicerjack

+1

什麼是「問題」?你傳遞給函數的是什麼? – Li357

+0

@Craicerjack我只發佈了代碼的錯誤部分,以避免我的問題被擱置或關閉。我應該發佈整個代碼嗎? –

回答

0

正如意見,JS說,做var myvar = some.thing並不能保證你在myvar有一個值。

如果some變量不包含thing屬性,然後some.thingundefined,所以會myvar

簡單演示here(使用左下方的控制檯按鈕)。最後一行會在您的瀏覽器控制檯中拋出一個錯誤,導致您無法執行undefined.someProperty