我正在制作一个简单的测验应用程序,其中包含多个问题。它没有后端,所有交互都发生在一个页面上。 我的对象布局如下 -
q1Choices = {
"question": "some question",
"resultsToRemoveIfAnswer1": [2, 4, 6],
"resultsToRemoveIfAnswer2": [1, 3, 5]
};
q2Choices = {
"question": "another question",
"resultsToRemoveIfAnswer1": [5, 6],
"resultsToRemoveIfAnswer2": [1, 2, 3, 4]
};
q3Choices = {
"question": "a third question",
"resultsToRemoveIfAnswer1": [3, 4],
"resultsToRemoveIfAnswer2": [1, 2]
};
一次出现一个问题,它有两个可能的答案 - 当单击一个答案时,会出现另一个问题,并从相应的对象填充。
为了允许这一点,我有一个计数器变量和一个带有对象的数组
var currentQuestion = 0;
var questionArray = [q1Choices, q2Choices, q3Choices];
我可以看到这段代码中有很多重复,并且正在寻找一种更干净、更易于维护、更 OO 的方式来做到这一点。
谁能给我任何指示?
为什么不只使用数组?
questions = [
[
"some question", //question
[2,4,6], //resultsToRemoveIfAnswer1
[1, 3, 5] //resultsToRemoveIfAnswer2
],
[
"another question",
[5, 6],
[1, 2, 3, 4]
],
...
]
然后,在"questions
项"中,可以将question
键作为索引 0、resultsToRemoveIfAnswer1
作为索引 1 访问,resultsToRemoveIfAnswer2
作为索引 2。
如果您不想依赖无意义的数字索引,请声明常量并使用它们
resultsToRemoveIfAnswer1 = 1
questions[0][resultsToRemoveIfAnswer1]
更多面向面向对象的示例:
function Questionary(){
const question = 0
const resultsToRemoveIfAnswer1 = 1
const resultsToRemoveIfAnswer2 = 2
this.questions = [
[
"some question",
[2,4,6],
[1, 3, 5]
],
[
"another question",
[5, 6],
[1, 2, 3, 4]
],
...
];
this.currentQuestion = 0;
}
//method example
Questionary.prototype.skipQuestion = function() {
return ++this.currentQuestion;
}
您可以更深入地添加具有text
、resultsToRemoveIfAnswer1
、resultsToRemoveIfAnswer2
等的Question
对象......