Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery check if number is in a list [duplicate]

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..

like image 848
Anders Avatar asked Jul 29 '13 18:07

Anders


3 Answers

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;
    };
}
like image 179
David Avatar answered Oct 20 '22 21:10

David


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.

like image 10
jdepypere Avatar answered Oct 20 '22 22:10

jdepypere


why dont you do a simple for loop?

for(var i = 0; i < array1.length; i++)
{
  if(array[i] == num)
   {
     //     do something
     break;
   }
}
like image 1
Armen Avatar answered Oct 20 '22 22:10

Armen