Domanda

I find myself often faced with a problem of reporting quiz results. Javascript gives me good ways to produce an objective score (e.g., 10 out of 20 correct answers), but I'm not sure of the best way to go about providing a subjective label of that result. E.g., "You scored 10 out of 20 correct answers, this is an average result."

To date, I've been doing this in a straight-forward manner:

if (score > 15) {
    answerText = "excellent";
} else if (score > 10) {
    answerText = "average";
} else if (score > 5) {
    answerText = "below average";
} else {
   answerText = "poor";
}

I wonder, though, if there is a better way to approach this. Is a switch statement better?

Advice and opinions appreciated!

È stato utile?

Soluzione

This is a perfectly fine way to approach this. You can use a reversed switch statement as well, but apart from the possible novelty effect it doesn't offer anything else:

switch (true) {
    case score > 15:
        answerText = "excellent";
        break;
    case score > 10:
        answerText = "average";
        break;
    // etc
}

If you want something more disciplined and maintainable you can create an array of threshold values and check each one of them in descending order, e.g.:

// This could also be an array of objects, but let's keep the PoC simple
var outcomes = [
    [15, "excellent"],
    [10, "average"],
    // ...
    [0, "poor"]
];

for (var i = 0; i < outcomes.length; ++i) {
    if (outcomes[i][0] <= score) {
        answerText = outcomes[i][1];
        break;
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top