dimanche 10 septembre 2017

Shorten long if else to get element from array based on value

I have an array of seven values, which might or might not get extended. Then I have a variable foo which is between 1 and -1. Based on foo, I select one element of my array, but I'm not really happy with the current solution.

Is there a preferred way of doing so?

Example:

// Of course there's useful data in no order like the alphabet
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
var foo = myFunc();  // Changes often between about 1 and -1
var index;

if (foo >= 0.1) {
    index = 6;
} else if (foo < 0.1 && foo >= 0.0) {
    index = 5;
} else if (foo < 0.0 && foo >= -0.1) {
    index = 4;
} else if (foo < -0.1 && foo >= -0.2) {
    index = 3;
} else if (foo < -0.2 && foo >= -0.3) {
    index = 2;
} else if (foo < -0.3 && foo >= -0.4) {
    index = 1;
} else {
    index = 0;
}

var element = myArray[index];

Thank you!

Aucun commentaire:

Enregistrer un commentaire