The Logical OR
operator doesn't work in a way you're looking for.
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
MDN
One alternative way could be make use of array's indexOf
method. Just be aware it will return the index
of the array element, so 0
could be a valid value also. In order to make our if
statement works as expected, we have to use 0 <= ...
like this:
if ( 0 <= ["apple","banana"].indexOf(a) ) { ... }
The other thing you can do is using in
operator. Also as it checks only against the keys
, you can leave the values
empty like this:
if ( a in { "apple": "", "banana": "" } ) { ... }
If you have lot's of options, obviously it's better to do the following:
var options = {
"apple": "",
"banana": ""
}
if ( a in options ) { ... }
Personally I think with just two options to check, this will be more readable for a human-eye to go for two separated checks, and I think in your examples you don't really need to shorten the if
statements as they're already quite short and readable in my opinion.
if ( "apple" === a || "banana" === a ) { ... }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…