Home >Web Front-end >JS Tutorial >How to compare a String with multiple String values ​​- javascript skills

How to compare a String with multiple String values ​​- javascript skills

WBOY
WBOYOriginal
2016-05-16 17:35:501108browse

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:

Copy the code The code is as follows:

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:
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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 IEjQuery
jQuery provides an inArray method
Copy code The code is as follows:

if ($.inArray(['banana', 'pineapple', 'mongo', 'lemon'], string) >= 0) {
fruitColor = 'yellow';
}

Underscore
Underscore provides a contains method
Copy code The code is as follows:

if (_.contains(['banana', 'pineapple', 'mongo', 'lemon'], string)) {
fruitColor = 'yellow ';
}

Regular expression
Of course, we also have the ultimate weapon - regular expression
Copy code The code is as follows:

if (/^(banana|pineapple|mongo|lemon)$/.test(string)) {
fruitColor = 'yellow';
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn