During development, we often need to compare one String and multiple String values. The intuitive reaction is to use the | symbol to connect multiple completions. If you are interested, you can understand that we often need to compare one String and multiple String values during development. The intuition is to use | symbol to connect multiple = complete, for example:
The Code is as follows:
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:
The Code is as follows:
If (string = 'bana' | 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
The Code is as follows:
Switch (string ){
Case 'bana ':
Case 'pineapple ':
Case 'mongo ':
Case 'limon ':
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
The Code is as follows:
If (['bana', 'pinape', 'mongo', 'lemon']. indexOf (string)> = 0 ){
FruitColor = 'yellow ';
}
This is much better, but there is another 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 the IE <= 8 environment, either write an indexOf method by yourself, or introduce some libraries for browser compatibility.
JQuery
JQuery provides an inArray method.
The Code is as follows:
If ($. inArray (['bana', 'pineapple', 'mongo ', 'lemon'], string)> = 0 ){
FruitColor = 'yellow ';
}
Underscore
Underscore provides a contains Method
The Code is as follows:
If (_. contains (['bana', 'pineapple', 'mongo ', 'lemon'], string )){
FruitColor = 'yellow ';
}
Regular Expression
Of course, we also have the ghost weapon-regular expression.
The Code is as follows:
If (/^ (banana | pineapple | mongo | lemon) $/. test (string )){
FruitColor = 'yellow ';
}