I have a long list of strings to compare against the same variable.
Is there a shorter way to do this?
if(val=="kivi" || val=="apples" || val=="lychee" || val=="banana.C" || val=="mangos")
To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.
The best way to test multiple variables for equality against a single value is to wrap the variables in a sequence (e.g. a set , a tuple , or a list ) and use the in operator. Using a set object should be slightly faster than the other sequences as set objects are optimized for membership testing.
To compare 3 values, use the logical AND (&&) operator to chain multiple conditions. When using the logical AND (&&) operator, all conditions have to return a truthy value for the if block to run. Copied!
Use the == operator to test if two variables are equal.
Use indexOf
with array of values
var valArr = ["kivi","apples","lychee","banana.C","mangos"];
if(valArr.indexOf(val) > -1){
.......
}
You can create an array and check if the value exists in array.
Array#includes
var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];
if (fruits.includes(val)) {
var fruits = ['kivi', 'apples', 'lychee', 'banana.C', 'mangos'];
document.getElementById('test').addEventListener('keyup', function() {
document.getElementById('result').textContent = 'Contains? ' + fruits.includes(this.value);
}, false);
<input type="text" id="test" />
<div id="result"></div>
Note that this is supported in latest browsers. However, polyfill can be used in older browsers.
Browser CompatibilityMDN
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