我正在嘗試用 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]);
}
}
這是我的 repo 的鏈接:DC Quiz
當我嘗試回答問題 4 時出現問題。在我的代碼中,您可以看到 main.js 檔案中第 206 行的錯誤。
感謝您的任何幫助!米歇爾
uj5u.com熱心網友回復:
將您的問題作為一個物件陣列并迭代它就像這里一樣簡單:
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
}]
;
uj5u.com熱心網友回復:
您需要將問題定義為一組物件。
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
}
];
uj5u.com熱心網友回復:
您還必須遍歷您的問題陣列。第一個問題是:
questions[0].question
順便說一句:你的問題變數應該是一個陣列。(就像您的答案一樣)嘗試以下操作:
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]);
}
}]
解釋:
問題陣列捆綁了所有問題物件。如果你想問一個特定的問題,你需要告訴 javascript 你想問哪個問題物件。
是第一個問題嗎?:
question[0].question
意思是:“一個正方形有幾條邊?”
或者另一個?
uj5u.com熱心網友回復:
我想,首先你可以迭代一系列問題,然后再檢查你的答案。但是,在我看來,您的問題的回購結構有點模棱兩可。目前尚不清楚答案是否包含測驗的答案集(如果是這樣,為什么要檢查此串列以獲取正確答案?我的意思是,無論如何,我想這組應該包含正確答案)或用戶答案索引(如果是這樣,您應該檢查值對答案陣列中的值的正確答案屬性中的索引)。
for (const question of questions) {
if ([check your answers with question.answers and question.correctAnswer]) {
[output: something like question.answers[question.correctAnswer]]
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366836.html
標籤:javascript 目的 索引
