Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: compare variable against array of values

In javascript I am doing the following which works fine.

if (myVar == 25 || myVar == 26 || myVar == 27 || myVar == 28)
 {
   //do something
 }

How can I shorten it? something like the following.

if (myVar IN ('25','26','27','28')) {
    //do something
   }

or

if(myVar.indexOf("25","26","27","28") > -1) ) {//do something}
like image 973
David Garcia Avatar asked Apr 16 '14 11:04

David Garcia


People also ask

How do you compare variables with arrays?

You can use Array. indexOf() , it returns the first index at which a given element can be found in the array, or -1 if it is not present. Array. includes() method can also be used it returns boolean .

How array is better as compare to variable?

Advantages over variables An array is considered to be a homogenous collection of data. Here the word collection means that it helps in storing multiple values which are under the same variable. For any purpose, if the user wishes to store multiple values of a similar type, an array is the best option that can be used.

How do you check all values of an array are equal or not in JavaScript?

In order to check whether every value of your records/array is equal to each other or not, you can use this function. allEqual() function returns true if the all records of a collection are equal and false otherwise.


3 Answers

You can use Array.indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

Use

var arr = [25, 26, 27, 28];
console.log(arr.indexOf(25) > -1);
console.log(arr.indexOf(31) > -1);

Array.includes() method can also be used it returns boolean.

var arr = [25, 26, 27, 28];
console.log(arr.includes(25));
console.log(arr.includes(31));
like image 77
Satpal Avatar answered Oct 10 '22 13:10

Satpal


Just try with:

if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}
like image 43
hsz Avatar answered Oct 10 '22 12:10

hsz


Other way :

myVar = (myVar == parseInt(myVar) ? myVar : false); //to check if variable is an integer and not float
if ( myVar >= 25 && myVar <= 28){}

Live demo

Edit based on the comment of Anthony Grist

This way works if you know what those values are going to be (i.e. they're not dynamic) and your array contains a series of consecutive numeric values.

like image 3
R3tep Avatar answered Oct 10 '22 12:10

R3tep