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;
}
Yeah, lookup array:
return [b, o, i, n, g][a - 1];
Not necessarily faster, but definetly shorter :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With