Sunday, 28 January 2018

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...