Sunday, January 28, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...