Skip to content Skip to sidebar Skip to footer

Conditional If For Many Values, Better Way

Is there a better way to deal with checking multiple values. It starts to get really busy when I have more than 3 choices. if (myval=='something' || myval=='other' || myval=='thir

Solution 1:

Solution 2:

Besides $.inArray, you could use Object notation:

if (myval in {'something':1, 'other':1, 'third':1}) {
   ...

or

if (({'something':1, 'other':1, 'third':1}).hasOwnProperty(myval)) {
   ....

(Note that the 1st code won't work if the client side has modified Object.prototype.)

Solution 3:

You can avoid iterating over the array by using some kind of a hash map:

var values = {
    'something': true,
    'other': true,
    'third': true
};

if(values[myVal]) {

}

Does also work without jQuery ;)

Solution 4:

a clean solution taken from the 10+ JAVASCRIPT SHORTHAND CODING TECHNIQUES:

longhand

if (myval === 'something' || myval === 'other' || myval === 'third') {
    alert('hey-O');
}

shorthand

if(['something', 'other', 'third'].indexOf(myvar) !== -1) alert('hey-O');

Post a Comment for "Conditional If For Many Values, Better Way"