我想在JS中制作一个调查应用,并且主要有以下代码:
for(var questionNumber in questionsAndAnswers.allQuestions){
for(var i in questionsAndAnswers.allQuestions[questionNumber]){
console.log(questionsAndAnswers.allQuestions[questionNumber].question);
console.log(questionsAndAnswers[questionNumber+1]);
}
}
而此代码在配置中:
const questionsAndAnswers = {
"allQuestions": [
{ "question": "Write your first question here",
},
{ "question": "Write your second question here",
},
{ "question": "Write your third question here",
}
],
"answerOne": [
"1.This is the first answer",
"1.This is the second answer",
"1.This is the third answer"
],
"answerTwo": [
"2.This is the first answer",
"2.This is the second answer",
"2.This is the third answer"
],
"answerThree": [
"3.This is the first answer",
"3.This is the second answer",
"3.This is the third answer"
]
}
然后出来:
Write your first question here
undefined
Write your second question here
undefined
Write your third question here
undefined
我想这样做:当问第一个问题时,仅出现第一个答案,但是当我致电
console.log(questionsAndAnswers[questionNumber+1]);
Undefined时出现。我尝试了许多选项,但是主要的问题是在更改
config
而不更改main
的情况下,将问题与答案分开,然后动态添加问题+答案。如果您能帮助我,我会非常高兴。
谢谢!
最佳答案
我认为您应该重新考虑您的数据模型。
您的questionsAndAnswers是一个对象,表示您不是通过整数而是通过键(“ answerOne”,“ answerTwo”,...)访问问题。
因此questionsAndAnswers[questionNumber+1]
不起作用。
它必须类似于questionsAndAnswers["answerOne"]
。
但是,我建议您将答案保存在问题对象中。
{
"question": "Write your first question here",
"answers": [...]
}