开发者

Simple OO structure for a quiz app - minimising repitition - improving OO skills

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 c开发者_如何学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?

questions = [
    [
        "some question", //question
        [2,4,6], //resultsToRemoveIfAnswer1
        [1, 3, 5] //resultsToRemoveIfAnswer2
    ],
    [
        "another question",
        [5, 6],
        [1, 2, 3, 4]
    ],
    ...
]

then, in questions items, you can access question key as index 0, resultsToRemoveIfAnswer1 as index 1, resultsToRemoveIfAnswer2 as index 2.

If you don't want to rely on meaningless numeric indexes declare constants and use them

resultsToRemoveIfAnswer1 = 1
questions[0][resultsToRemoveIfAnswer1]

More OO oriented sample:

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;
}

and you can go deeper adding a Question Object with text, resultsToRemoveIfAnswer1, resultsToRemoveIfAnswer2 and so on...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜