Becky Becky - 7 months ago 21
Javascript Question

Compare multiple values against the same variable

I have a long list of strings to compare against the same variable.

Is there a shorter way to do this?

if(val=="kivi" || val=="apples" || val=="lychee" || val=="banana.C" || val=="mangos")

Answer

Use indexOf with array of values

var valArr = ["kivi","apples","lychee","banana.C","mangos"];

if(valArr.indexOf(val) > -1){
   .......
}