In development, we often need to compare a String with multiple String values. The intuitive reaction is to use the || symbol to connect multiple === completions, such as:
if (string === 'banana' || string === 'pineapple') {
fruitColor = 'yellow';
}
This can be very easy Good for completing the needs, but it always feels a bit clumsy and not friendly to expansion. When our fruit types increase:
if (string === 'banana' || string === 'pineapple' || string === 'mongo' || string === 'lemon') {
fruitColor = 'yellow';
}
The above code doesn’t look that good, let’s see if there are any other ways to handle this requirement.
Switch
switch( string) {
case 'banana':
case 'pineapple':
case 'mongo':
case 'lemon':
fruitColor = 'yellow';
}
This looks good, but it always requires more typing and is not a good method for people who don’t like to type a lot.
Array
if ( ['banana', 'pineapple', 'mongo', 'lemon'].indexOf(string) >= 0) {
fruitColor = 'yellow';
}
This is much better, but there is still a problem. IE browsers below IE9 do not support the indexOf method. If you want to use the Array method to compare multiple string values in an IE
jQuery jQuery provides an inArray method
if ($.inArray(['banana', 'pineapple', 'mongo', 'lemon'], string) >= 0) {
fruitColor = 'yellow';
}
Underscore Underscore provides a contains method
if (_.contains(['banana', 'pineapple', 'mongo', 'lemon'], string)) {
fruitColor = 'yellow ';
}
Regular expression Of course, we also have the ultimate weapon - regular expression
if (/^(banana|pineapple|mongo|lemon)$/.test(string)) {
fruitColor = 'yellow';
}