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")
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")
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.
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.
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...
}
One line check:
if (['kivi', 'apples', 'lychee', 'banana.C', 'mangos'].includes(val)) {
// Some code
}
myArr = ["kivi", "apples", "lychee", "banana.C", "mangos"];
if(myArr.indexOf(val) != -1)
{
// Element Found!!
}