Javascript if else loop?

  • A+

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

EDIT: Having an issue with the first letter. The above code is what the following answers are focusing on, so please ignore all of this as it's not entirely relevant to the overarching question.

var rotate=0; var count=0; $(".target span").each(function() {             var num = Math.floor(Math.random()*20) + 1; // this will get a number between 1 and 10; function isOdd(x) { return x % 2;}  if(isOdd(count)==1){      rotate = rotate+num;      alert(rotate);      alert(count);             $(this).css({             "-webkit-transform": "rotate("+rotate+"deg)",             "display": "inline-block",             "color": boingColours(count)             }); }else{     rotate = Math.abs(rotate+num);     alert(rotate);       alert(count);             $(this).css({             "-webkit-transform": "rotate("+rotate+"deg)",             "display": "inline-block",             "color": boingColours(count)             }); }                  count++;      });      function boingColours(a) {     var b = "#ff0002";     var o = "#46c029";     var i = "#f2ec00";     var n = "#f64c98";     var g = "#52c6f3";     return [b, o, i, n, g][a - 1]; } 


Yeah, lookup array:

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

Not necessarily faster, but definetly shorter :)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: