I need to use the OR operator in a jQuery if statement to filter out 10 states. My code works wile only excluding one state, but fails when i try to include multiple states. Is there a correct way to do this?
Code I am am using :
if ((state != 10) || (state != 15) || (state != 19) ||
(state != 22) || (state != 33) || (state != 39) ||
(state != 47) || (state != 48) || (state != 49) ||
(state != 51))
return true;
Thanks
This question is related to
jquery
if-statement
operators
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
The code you wrote will always return true
because state
cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15)....
AND
is what you need not OR
.
Use $.inArray instead. This returns the index of the element in the array.
var statesArray = [10, 15, 19]; // list out all
var index = $.inArray(state, statesArray);
if(index == -1) {
console.log("Not there in array");
return true;
} else {
console.log("Found it");
return false;
}
The logical OR '||' automatically short circuits if it meets a true condition once.
false || false || true || false = true, stops at second condition.
On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.
false && true && true && true = false, stops at first condition.
Source: Stackoverflow.com