可能是一些非常基本的東西,但我正在嘗試撰寫一個簡單的 JS 測驗,并且我有一個用于問題、選擇和答案的陣列:
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
},
ETC..
我可以從陣列中選擇一個特定的問題,但不能從中選擇相關的選擇或答案。
function grabQuestion() {
for (let i = 0; i < questions.length; i ) {
const question = questions[i].question
const choices = questions[i].choices
questionEl.textContent = question
console.log(choices)
console.log(answer)
}
}
這只是列出了所有 questions.choices,而不是我在 for 回圈中生成的索引。
我知道這很簡單,但我只是沒有看到它。
uj5u.com熱心網友回復:
根據我的理解,您想獲取特定問題的choices
andanswer
以獲得所有答案和選擇?如果是,那么您可以根據問題從陣列中動態獲取它,或者通過為每個問題物件text
分配一個。id
讓我用一個例子/演示來解釋:
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
}];
function getQuestionDetails(questionText) {
return questions.find(({ question }) => questionText === question);
}
const selectedQuestionDetails = getQuestionDetails('What is JavaScript?');
console.log('choices', selectedQuestionDetails.choices);
console.log('answer', selectedQuestionDetails.answer);
uj5u.com熱心網友回復:
你只是忘了定義answer
我認為。只需添加這個。
const answer = questions[i].answer
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488464.html
標籤:javascript 数组 for循环 索引