I have JavaScript code in my app that checks values using the OR(||) condition as in code snippet below. The number of OR conditions is not small in most of my code.
Question : Is there a way to make the code that has many multiple OR conditions more concise by using something like this: value IN ('s','b','g','p','z')
? I was interested in something that comes as close as possible to an IN clause.
if(value === "s" || value === "b" || value === "g" || value === "p" || value === "z") {
//do something
}
The simplest way is to create an array of valid values, then make sure your value is in that list. You can use the indexOf
method for that:
var allowed = ['s', 'b', 'g', 'p', 'z'];
if (allowed.indexOf(value) !== -1) {
// do something
}
The ES6 standard introduces Sets, which has a has
method to do a similar thing on unique values.
This will work for strings, numbers, and other simple non-object values. Comparing objects with ===
will only succeed if the array/set already contains the exact same object.
You can also use javascript .includes()
helper.
The
includes()
method determines whether an array includes a certain element, returningtrue
orfalse
as appropriate.
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
You could do something like this:
var values = ['s','b','g','p','z'];
if (values.indexOf(value) > -1)
There is, in fact, an in
in JavaScript and it can be used for your case exactly. Construct a dictionary with any values you like, but using your allowed letters as the keys:
allowed = { 's':true, 'b':true, 'g':true, 'p':true, 'z':true };
Now you can use the in
test directly (and more efficiently than a lookup in a list). Here copied from my JavaScript console:
's' in allowed
true
'q' in allowed
false
A solution for single characters:
var value = 'g'; if (~'sbgpz'.indexOf(value)) { document.write(value + ' found'); }
A solution for strings characters:
var value = 'go'; if (~['so', 'bo', 'go', 'po', 'zo'].indexOf(value)) { document.write(value + ' found'); }
A 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]();
Why not lodash's includes
function?
var val = 's';
var criterion = ['s','b','g','p','z'];
_.includes(criterion, val);
returns true
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.