首先,对不起我的英语,希望我能够很好地向你解释我的问题。
我想创建一个基于主题的测验,我需要帮助构建包含主题,问题和答案的数组。到目前为止我得到了这个:
var aarhus={
question: 'Is this a aarhus question?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
var multimedia={
question: 'Is this a multimedia question?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
var general={
question: 'Is this a general question?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
我有3个代表主题的数组。他们存储问题,4个可能的答案和正确的答案。问题是我在每个主题中只有一个问题。所以我的问题是 - 如何向主题添加更多问题?我需要能够在主题内使用它的答案来访问任何问题(假设有2个问题,每个主题都有自己的答案)。
谢谢!
答案 0 :(得分:3)
只是为了挑剔,这些是“普通”对象,而不是数组。但是,您可以使用嵌套对象和数组对问题进行分组:
var questions =
{
theme1:
[
{
question: "this is question 1",
answers: ["one", "two", "three"],
correct: "two"
},
{
question: "this is question 2",
answers: ["one", "two", "three"],
correct: "three"
}
],
theme2:
[
{
question: "this is question 1",
answers: ["one", "two", "three"],
correct: "two"
},
{
question: "this is question 2",
answers: ["one", "two", "three"],
correct: "three"
}
]
}
//To access the second question of theme 2
questions.theme2[1].question
答案 1 :(得分:1)
只需将主题设为数组:
var general=[{
question: 'Is this a general question?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
}];
然后,您可以使用array.push
向主题添加新问题:
general.push({
question: 'Is this a second general question?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
});
像访问任何数组一样访问它们:
var questionIndex = 1; // question #2 in the theme
console.log(general[questionIndex].question); // "Is this a second general question?"
答案 2 :(得分:1)
也许这个解决方案会有所帮助:
<html><head><title>Test</title></head>
<script>
var MULTIMEDIA = 'Multimedia';
var question1 = {
question: 'Is this a multimedia question1?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
var question2 = {
question: 'Is this a multimedia question2?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
var question3 = {
question: 'Is this a multimedia question3?',
answer1:'yes',
answer2:'no',
answer3:'I dunno',
answer4:'stfu',
correctAnswer:'stfu'
};
var questions = [];
questions[0] = question1;
questions[1] = question2;
questions[2] = question3;
var theme = {
questions : questions
}
var themes = [];
themes[MULTIMEDIA] = theme;
</script>
<body>
<label>
<script>
var questionNo = 0;
document.write(themes[MULTIMEDIA].questions[questionNo].question + '<br>');
document.write('<ul>');
document.write('<li>' + themes[MULTIMEDIA].questions[questionNo].answer1 + '</li>');
document.write('<li>' + themes[MULTIMEDIA].questions[questionNo].answer2 + '</li>');
document.write('<li>' + themes[MULTIMEDIA].questions[questionNo].answer3 + '</li>');
document.write('</ul>');
</script>
</label>
</body>
</html>