I was just wondering if there is some JS shorthand for something like this:
if (x != 1 && x != 2) do stuff;
Does such a beast exist? Instead, I want to say something like this:
if (x != 1:2) do stuff;
No, there is no such shorthand.
You can use a switch if you don't want to repeat the variable:
switch (x) {
case 1:
case 2: break;
default: do stuff;
}
Another alternative would be to look for the value in an array:
if ([1, 2].indexOf(x) == -1) do stuff;
However, the Array.indexOf
doesn't exist in all browsers, so you may need a fallback which you can for example find on the Mozilla Array.indexOf
documentation page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With