Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if else loop?

I'm sure there probably is, however I'm not sure what it's called so apologises if this is something super similar. I'm wondering if there's a faster way to code the following:

var b = "#ff0002";
var o = "#46c029";
var i = "#f2ec00";
var n = "#f64c98";
var g = "#52c6f3";

if(a==1){
    return b;
}else if(a==2){
    return o;
}else if(a==3){
    return i;
}else if(a==4){
    return n;
}else if(a==5){
    return g;
}
like image 923
Larm Avatar asked Dec 04 '22 19:12

Larm


2 Answers

Yeah, lookup array:

return [b, o, i, n, g][a - 1];

Not necessarily faster, but definetly shorter :)

like image 107
Jonas Wilms Avatar answered Dec 06 '22 11:12

Jonas Wilms


If you have large number of strings to compare from use Object like this:

myObj = {1: '#ff0002', 2: '#46c029', 3: "#f2ec00", 4: "#f64c98", 5: "#52c6f3"}

console.log(myObj[3]);

If you are using ES6 you can use Map() like this:

const myMap = new Map([[1, '#ff0002'], [2, '#46c029'], [3, "#f2ec00"], [4, "#f64c98"], [5, "#52c6f3"]])

console.log(myMap.get(3)); // or any key
like image 24
BlackBeard Avatar answered Dec 06 '22 10:12

BlackBeard