简体   繁体   中英

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=='third') {

}

PHP has a function called in_array() that's used like this:

in_array($myval, array('something', 'other', 'third')) 

Is there something like it in js or jquery?

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 .)

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 ;)

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM