Thursday 11 July 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...