Compare multiple values against the same variable [duplicate]
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")
Solution 1:
Use indexOf
with array of values
var valArr = ["kivi","apples","lychee","banana.C","mangos"];
if(valArr.indexOf(val) > -1){
.......
}
Solution 2:
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
Solution 3:
Nope. That's about as short as it gets for direct string comparison.
If you have a lot of values to compare against you could put those values in an array and use indexOf
, like this:
var comparisons = ["kivi", "apples", "lychee", "banana.C", "mangos" ];
if (comparisons.indexOf(val) != -1) {
// do something...
}
Solution 4:
myArr = ["kivi", "apples", "lychee", "banana.C", "mangos"];
if(myArr.indexOf(val) != -1)
{
// Element Found!!
}