During development, we often need to compare one string and multiple string values. The intuitive response is to use||Multiple symbols are connected.===Completed, for example:
if (string === 'banana' || string === 'pineapple') { fruitColor = 'yellow';}
In this way, the demand can be well met, but it is always a bit stupid and unfriendly to expansion. When we have more fruit types:
if (string === 'banana' || string === 'pineapple' || string === 'mongo' || string === 'lemon') { fruitColor = 'yellow';}
The above Code does not look so nice. Let's see what other methods can be used 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 words. It is not a good method for people who do not like to type more words.
Array
if (['banana', 'pineapple', 'mongo', 'lemon'].indexOf(string) >= 0) { fruitColor = 'yellow';}
This is much better, but there is still a problem that IE browsers below ie9 do not supportindexOfMethod. If you want to use the array method to compare multiple string values in the IE <= 8 environment, or writeindexOfMethod, or you have to introduce some libraries for browser compatibility.
Jquery
Jquery provides an inarray method.
if ($.inArray(['banana', 'pineapple', 'mongo', 'lemon'], string) >= 0) { fruitColor = 'yellow';} Underscore
Underscore providescontainsMethod
if (_.contains(['banana', 'pineapple', 'mongo', 'lemon'], string)) { fruitColor = 'yellow';} Regular Expression
Of course, we also have the ghost weapon-regular expression.
if (/^(banana|pineapple|mongo|lemon)$/.test(string)) { fruitColor = 'yellow';}