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}
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 .
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.
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.
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));
Just try with:
if ( [25, 26, 27, 28].indexOf(myVar) > -1 ) {}
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.
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