gpt4 book ai didi

javascript - 类型错误 : q is undefined (in JS)

转载 作者:行者123 更新时间:2023-11-28 05:10:21 25 4
gpt4 key购买 nike

我必须按照视频中的说明制作一个测验应用程序。我按照说明制作应用程序。几乎一切都有效,但测验结束时我没有得到任何分数。 Web 控制台在以下代码部分中显示 TypeError(第 16 行以粗体显示):

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"
}]

最佳答案

正如评论中所说,在 JS 中,执行 var myvar = some.thing 并不能保证您在 myvar 中有一个值。

如果 some 变量不包含 thing 属性,则 some.thing未定义,因此将是myvar

简单演示 here (使用左下角的控制台按钮)。最后一行将在浏览器控制台中抛出错误,导致您无法执行 undefined.someProperty

关于javascript - 类型错误 : q is undefined (in JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41435089/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com