How to compare one String and multiple String values

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.