Compare multiple values โ€‹โ€‹with the same variable

I have a long list of strings to compare with the same variable.

Is there a shorter way to do this?

if(val=="kivi" || val=="apples" || val=="lychee" || val=="banana.C" || val=="mangos") 
+5
source share
4 answers

Use indexOf with an array of values

 var valArr = ["kivi","apples","lychee","banana.C","mangos"]; if(valArr.indexOf(val) > -1){ ....... } 
+9
source

You can create an array and check if a value exists in the 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> 

Please note that this is supported in recent browsers. However, polyfill can be used in older browsers.

MDN Browser Compatibility

+3
source

Nope. This is about as short as for direct string comparisons.

If you have many values โ€‹โ€‹to compare, you can put these values โ€‹โ€‹in an array and use indexOf , for example:

 var comparisons = ["kivi", "apples", "lychee", "banana.C", "mangos" ]; if (comparisons.indexOf(val) != -1) { // do something... } 
+3
source
 myArr = ["kivi", "apples", "lychee", "banana.C", "mangos"]; if(myArr.indexOf(val) != -1) { // Element Found!! } 
0
source

Source: https://habr.com/ru/post/1247927/


All Articles