JavaScript中如何按索引校验数组内题目对象的正确答案
问题解决方法
核心故障原因
- 多题目定义时缺失数组包裹符
[]:你第二段代码的赋值逻辑使用逗号运算符,最终questions只会被赋值为最后一个题目对象,而非预期的题目集合数组。 - 没有适配数组的访问逻辑:就算
questions是数组,数组本身不存在answers、correctAnswer这类题目专属属性,你需要先遍历数组拿到单道题目对象,再执行原有匹配逻辑。
修复后可运行代码
// 用方括号包裹所有题目,将questions定义为题目数组 let questions = [ { question: "How many sides does a square have?", answers: [4, 6, 8], correctAnswer: 0 }, { question: "How many sides does a triangle have?", answers: [3, 6, 8], correctAnswer: 0 } ]; // 先遍历数组中的每一道题目 for (const singleQuestion of questions) { const iterator = singleQuestion.answers.keys(); for (const key of iterator) { if (key === singleQuestion.correctAnswer) { console.log(singleQuestion.question + ": " + singleQuestion.answers[key]); } } }
答题校验逻辑优化建议
实际做用户答题判断时不需要遍历所有选项的索引,直接对比用户选中的索引和当前题目正确答案索引即可,性能更高:
// 示例:判断用户答当前第2题(数组索引为1)选了第1个选项(索引为0)是否正确 const currentQuestionIndex = 1; const userSelectIndex = 0; const judgeResult = userSelectIndex === questions[currentQuestionIndex].correctAnswer; console.log(judgeResult ? '回答正确' : '回答错误');
内容的提问来源于stack exchange,提问作者Michiel
相关产品推荐
相关产品推荐

