Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 672
Becky Avatar asked Apr 26 '16 10:04

Becky


People also ask

How do you compare variables with multiple values?

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.

How do you test multiple variables for equality against a single value?

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.

How do you compare three values?

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!

How do you know if two variables are similar?

Use the == operator to test if two variables are equal.


2 Answers

Use indexOf with array of values

var valArr = ["kivi","apples","lychee","banana.C","mangos"];

if(valArr.indexOf(val) > -1){
   .......
}
like image 154
Pranav C Balan Avatar answered Oct 17 '22 17:10

Pranav C Balan


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

like image 5
Tushar Avatar answered Oct 17 '22 17:10

Tushar