【发布时间】:2022-01-04 09:15:25
【问题描述】:
我正在尝试用 JavaScript 构建一个测验。我有一个带有问题、答案和正确答案的对象。我可以通过将答案中的索引与正确答案的索引进行匹配来检查用户是否正确回答了问题。
但是,当我尝试使用多个对象并尝试运行此代码时,它不起作用。我怎样才能做到这一点?`
这行得通:
let questions = {
question: "How many sides does a square have?",
answers: [4, 6, 8],
correctAnswer: 0,
category: "trueOrFalse"
};
const iterator = questions.answers.keys();
for (const key of iterator) {
if (key === questions.correctAnswer) {
console.log(questions.question + ": " + questions.answers[key]);
}
}
但这不起作用:
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
}
;
const iterator = questions.answers.keys();
for (const key of iterator) {
if (key === questions.correctAnswer) {
console.log(questions.question + ": " + questions.answers[key]);
}
}
这是我的仓库的链接:DC Quiz
当我尝试回答问题 4 时出现问题。在我的代码中,您可以在第 206 行的 main.js 文件中看到它有问题。
感谢您的帮助! 米歇尔
【问题讨论】:
标签: javascript object indexing