编写简单JS测验时如何访问变量中定义的对应选项与答案
问题原因与修复方案
你的代码存在两个直接导致异常的问题:
- 函数内的for循环会遍历全部题目数组,每轮循环都会覆盖
questionEl的文本内容,循环执行完成后页面只会保留最后一道题的内容,控制台也会按遍历顺序输出所有题目的选项,自然无法匹配单题内容。 - 没有从当前遍历的题目对象中提取
answer属性,直接执行console.log(answer)本身就会因为变量未定义报错。
如果要实现单题依次展示的常规测验逻辑,不需要在取题函数里写全量数组循环,单独维护一个当前题目的索引变量即可,参考实现如下:
// 题目数组补全闭合 const questions = [ { question: "What is JavaScript?", choices: ["An interesting coffee blend", "Something your doctor uses", "A new movie", "A coding language"], answer: 3 }, { question: "Which of the following keywords is used to define a variable?", choices: ["var", "let", "Both A and B", "None of the above"], answer: 2 } ] // 全局维护当前展示的题目索引,初始加载第一题(数组索引从0开始) let currentQuestionIndex = 0 // 替换成你实际的DOM元素获取逻辑 const questionEl = document.querySelector('#question-title') const choicesContainer = document.querySelector('#choices-wrap') function grabQuestion() { // 直接取当前索引对应的单题对象,无需遍历全量数组 const activeQuestion = questions[currentQuestionIndex] // 渲染题干 questionEl.textContent = activeQuestion.question // 获取当前题的选项、正确答案 const activeChoices = activeQuestion.choices const activeAnswer = activeQuestion.answer // 清空旧选项,渲染新题的选项列表 choicesContainer.innerHTML = '' activeChoices.forEach((choiceText, choiceIndex) => { const choiceBtn = document.createElement('button') choiceBtn.textContent = choiceText // 绑定选项点击判分逻辑 choiceBtn.addEventListener('click', () => { if (choiceIndex === activeAnswer) { alert('回答正确') // 切换到下一题 currentQuestionIndex++ currentQuestionIndex < questions.length ? grabQuestion() : alert('测验已完成') } else { alert('回答错误,请重试') } }) choicesContainer.appendChild(choiceBtn) }) // 控制台仅输出当前题的关联数据,不会混入其他题目内容 console.log('当前题选项:', activeChoices) console.log('当前题正确答案索引:', activeAnswer) } // 页面加载完成后渲染第一题 grabQuestion()
如果你需要一次性渲染所有题目,那循环过程中需要为每道题单独创建独立的DOM容器,不能反复给同一个questionEl赋值,否则永远只会显示最后一道题的内容。
内容的提问来源于stack exchange,提问作者Matt L
相关产品推荐
相关产品推荐

