I’m making a simple quiz application which has multiple questions. It has no back end and all of the interaction happens on one page. my objects are laid out as follows –
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]
};
One question appears at a time, which has two possible answers – when an answer is clicked another question appears and is populated from the corresponding object.
To allow for this, I have a counter variable and an array with the objects
var currentQuestion = 0;
var questionArray = [q1Choices, q2Choices, q3Choices];
I can see there is a lot of repetition in this code and was looking for a cleaner, more maintainable, more OO way of doing it.
Can anyone give me any pointers?
Why don’t you use arrays only?
then, in
questionsitems, you can accessquestionkey as index 0,resultsToRemoveIfAnswer1as index 1,resultsToRemoveIfAnswer2as index 2.If you don’t want to rely on meaningless numeric indexes declare constants and use them
More OO oriented sample:
and you can go deeper adding a
QuestionObject withtext,resultsToRemoveIfAnswer1,resultsToRemoveIfAnswer2and so on…