Friday 21 October 2016

javascript - jquery check if number is in a list




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



Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...