2 回答
TA贡献1942条经验 获得超3个赞
只是语法错误。每个嵌套对象后面的分号应该只是逗号。看:
let allQuestions = {
question1: {
question: 'You should ______ if a large animal is in your path and you cant stop in time.',
ans1: 'Brake hard',
ans2: 'Hit the animal at an angle',
ans3: 'Take your foot of the brakes so it doesnt go through your windshield',
ans4c: 'All of the above'
},
question2: {
question: 'How come motorcyclists often ride in the left part of the lane?',
ans1: 'They can pass cyclists on the right part of the lane'
}, //(optional comma here)
};
TA贡献1847条经验 获得超7个赞
这里已更正。
let allQuestions = {
question1: {
question: 'You should ______ if a large animal is in your path and you cant stop in time.',
ans1: 'Brake hard',
ans2: 'Hit the animal at an angle',
ans3: 'Take your foot of the brakes so it doesnt go through your windshield',
ans4c: 'All of the above'
},
question2: {
question: 'How come motorcyclists often ride in the left part of the lane?',
ans1: 'They can pass cyclists on the right part of the lane'
}
};
console.log(allQuestions);
但是您是否考虑过结构本身,使用数组,以便可以更轻松地迭代代码。
let allQuestions = [{
question: 'You should ______ if a large animal is in your path and you cant stop in time.',
answers: [{
id: 1,
answer: 'Brake hard'
},
{
id: 2,
answer: 'Hit the animal at an angle'
},
{
id: 3,
answer: 'Take your foot of the brakes so it doesnt go through your windshield'
},
{
id: 4,
answer: 'All of the above'
}
]
},
{
question: 'How come motorcyclists often ride in the left part of the lane?',
answers: [{
id: 1,
answer: 'They can pass cyclists on the right part of the lane'
}]
}
];
console.log(allQuestions);
因此,现在使用数组,我们可以轻松构建HTML
let allQuestions = [{
question: 'You should ______ if a large animal is in your path and you cant stop in time.',
answers: [{
id: 1,
answer: 'Brake hard'
},
{
id: 2,
answer: 'Hit the animal at an angle'
},
{
id: 3,
answer: 'Take your foot of the brakes so it doesnt go through your windshield'
},
{
id: 4,
answer: 'All of the above'
}
]
},
{
question: 'How come motorcyclists often ride in the left part of the lane?',
answers: [{
id: 1,
answer: 'They can pass cyclists on the right part of the lane'
}]
}
];
const getAnswerHtml = (answers) => answers.map(a => `<li id="${a.id}">${a.answer}</li>`).join('');
const getQuestionHtml = (question) => `<div class="question"><h3>${question.question}</h3><ul>${getAnswerHtml(question.answers)}</ul></div>`;
document.querySelector('.questions').innerHTML = allQuestions.map(q => getQuestionHtml(q)).join('');
<div class="questions"></div>
添加回答
举报