I have to check whether a variable is equal to a given number or another. For example I am doing this right now.
if (num == 1 || num == 3 || num == 4 || etc.) {
// Do something
} else if (num == 2 || num == 7 || num == 11 || etc.) {
// Do something
}
I thought there should be an easier way. for example an array of all numbers per if statement.
var array1 = [1,3,4,5,6,8,9,10 etc.]
var array2 = [2,7,11,12,13,14 etc.]
And then see if the number is equal to anything inside one of these arrays. But I don't know how to do it..
The indexOf() method searches the array for the specified item, and returns its position.
var array1 = [1,3,4,5,6,8,9,10];
var a = array1.indexOf(46); //a = -1; if not found
If you need to support environments that don't have .indexOf(), you could implement the MDN fix.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this === void 0 || this === null) throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) return -1;
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n !== n) // shortcut for verifying if it's NaN
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len) return -1;
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) return k;
}
return -1;
};
}
Since you're asking for jQuery, there is .inArray(). This returns a -1
if it isn't found, else the index of the matching element.
why dont you do a simple for loop?
for(var i = 0; i < array1.length; i++)
{
if(array[i] == num)
{
// do something
break;
}
}
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