IN using JavaScript code

I have JavaScript code in my application that checks the values ​​using the OR (||) condition, as in the code snippet below. The number of OR conditions in most of my codes is small.

Question Is there a way to make code that has multiple conditions OR more concise using something like this: value IN ('s','b','g','p','z') ? I was interested in being as close as possible to the IN clause.

 if(value === "s" || value === "b" || value === "g" || value === "p" || value === "z") { //do something } 
+4
source share
6 answers

Why doesn't lodash include a function?

 var val = 's'; var criterion = ['s','b','g','p','z']; _.includes(criterion, val); 

returns true ;

0
source

The easiest way is to create an array of valid values ​​and then make sure your value is on this list. You can use the indexOf method to do this:

 var allowed = ['s', 'b', 'g', 'p', 'z']; if (allowed.indexOf(value) !== -1) { // do something } 

The ES6 standard introduces Sets, which a has method does a similar thing for unique values.

This will work for strings, numbers, and other simple values ​​other than an object. Comparing objects with === will succeed only if the array / set already contains the same object.

+4
source

You can do something like this:

 var values = ['s','b','g','p','z']; if (values.indexOf(value) > -1) 
+1
source

JavaScript is essentially in , and it can be used for your case for sure. Build a dictionary with any values ​​you like, but using your allowed letters as keys:

 allowed = { 's':true, 'b':true, 'g':true, 'p':true, 'z':true }; 

Now you can directly use the in test (and more efficiently than searching the list). Here's the JavaScript copied from my console:

 's' in allowed true 'q' in allowed false 
+1
source

Single character solution:

 var value = 'g'; if (~'sbgpz'.indexOf(value)) { document.write(value + ' found'); } 

Solution for string characters:

 var value = 'go'; if (~['so', 'bo', 'go', 'po', 'zo'].indexOf(value)) { document.write(value + ' found'); } 

Solution for object properties:

 var value = 'go'; var toDo = { so: function () { document.write('prop so found'); }, go: function () { document.write('prop go found'); } }; value in toDo && toDo[value](); 
+1
source

You can also use the javascript .includes() helper.

The includes() method determines whether the array contains an element, returning true or false as necessary.

 var array1 = [1, 2, 3]; console.log(array1.includes(2)); // expected output: true var pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false 
0
source

All Articles