Skip to content Skip to sidebar Skip to footer

Does Javascript Have A Way To Do "in" When I Want To See If A Value Is One Of Many?

My code looks like this: if (testStatusId == 4 || testStatusId == 5) { This is just a simplified version for the question. Does Javascript have anything like an 'in' where I would

Solution 1:

You could make an array like:

if([4,5].includes(testStatusId)) { ... }

You'll need a polyfill for it as it's not universally supported. (ex: https://www.npmjs.com/package/array-includes-polyfill)

You could use indexOf with the same approach with wider compatibility:

if([4,5].indexOf(testStatusId) !== -1) { ... }

Solution 2:

var j = [4,5];
if(j.indexOf(testStatusId) !== -1){
//your code here
}

Solution 3:

switch (testStatusId)
{
       case 4:
       case 5:
          // do whatever
          break;

       case 6:
          // something else
          break;

       default:
          // everything else
}

Solution 4:

You could do this:

if([4,5].indexOf(testStatusId) !== -1) {
}

Although the code you have is probably already the best, if they is only two numbers.


Post a Comment for "Does Javascript Have A Way To Do "in" When I Want To See If A Value Is One Of Many?"