Вопрос

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;

Это было полезно?

Решение 2

No that doesn't exist, and that is good! Only in less precise natural language does such a thing exist, which can lead to confusion.

Другие советы

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.

There are two ways I can think of.

Case 1:

if ([1, 2].indexOf(x) < 0) // do stuff

Case 2:

I wouldn't recommend this way:

if (!(x in {1:0, 2:0})) // do stuff

Stepwise:

  1. We create an object with the numbers to compare against as keys: {1:0, 2:0}
  2. We use the in operator to check whether the value of x is a key of the object.
  3. We negate the resultant boolean using ! because we want to check for inequality.

I suggest you look at CoffeeScript instead. It has chained comparisons which will allow you to do something like this:

if (1 <= x <= 2) // do stuff

It's not the same as your condition, but you might find it interesting.

var a = 4;
if ([1,2,3,5,7,8,9,0,10,15,100].indexOf(a) == -1) console.log(a);

Will log 4 to console because 4 is not present on the list.

x!=1 && x!=2 is shorthand for the browser- if the first part is false it quits right away. No code you can wrap it in that evaluates both expressions could be nearly as efficient.

There would be nothing wrong with writing your own function to add a method to a given object. There are a variety of ways to do that, by extending prototypes or using a namespace. Example syntax might be:

if (!x.equals('1||2')) { /* do your stuff */ }
// the custom method '.equals' would extend a STRING, and return true or false

Another example:

if (π.is(x,['1||2'])) { /* do your stuff */ }
// custom object "π" has a method "is" which checks whether x is 1 or 2, and returns true or false

There are so many ways to do this. Some are frowned upon for very good reasons (extending core object prototypes, for example, is not always ideal as it could impact other libraries and freak people out), and of course there is always the risk of over-engineering. Tread carefully.

Minor note: I intentionally put the logical operator '||', with the idea that the underlying function might be flexible and take other operators, such as '&&' or '!' etc.

You can now use .includes:

![1, 2].includes(x);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top