Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a faster way of writing OR operator?

Tags:

javascript

Is there a faster way of writing this?

if ($('#id').val()==7 || $('#id').val()==8 || $('#id').val()==9){
    console.log('value of #id is 7, 8, or 9!')
};

I'm thinking of something like:

if ($('#id').val()== 7||8||9){
    console.log('value of #id is 7, 8, or 9!')
};
like image 677
quelquecosa Avatar asked Jan 29 '14 20:01

quelquecosa


1 Answers

You can use indexOf(), it returns the first index at which a given element can be found in the array, or -1 if it is not present.

if ([7,8,9].indexOf(+$('#id').val()) > -1){
    console.log('value of #id is 7, 8, or 9!')
};

The above function will work in IE9+, for older browser's you can use either PolyFill or jQuery.inArray(value, array)

if (jQuery.inArray(+$('#id').val(),[7,8,9]) > -1){
    console.log('value of #id is 7, 8, or 9!')
};
like image 50
Satpal Avatar answered Oct 02 '22 09:10

Satpal