简体   繁体   中英

Reduce number of if else statements?

I have some JavaScript, when a user enters in 10 digits in the phone field,it checks whether the country field has been populated so that it can assign a country code to it. See code below.

if (Country != null) {
    var CountryName = Country[0].name;
    var CountryId = Country[0].id;
    var CountryType = Country[0].entityType;
    if (CountryName == "United States of America") {
        PhoneTemp = "+1 " + "(" + PhoneTemp.substr(0, 3) + ") " + PhoneTemp.substr(3, 3) + " - " + PhoneTemp.substr(6, 4);
    } else if (CountryName == "India") {
        PhoneTemp = "+91 " + PhoneTemp.substr(0, 4) + " " + PhoneTemp.substr(4, 6);
    }
}

If i do it this way ill end up with a 100+ else if, is there a nicer way of doing it?

You can use switch or you can use Jquery $.inArray(val, array)

I would go for a map to abstract the country logic

var countryMap = {
  'USA': usaLogic,
  'FR': frLogic
};

function usaLogic(number) {
   return "+1 " + "(" + number.substr(0, 3) + ") " + number.substr(3, 3) + " - " + number.substr(6, 4);
}

function frLogic(number) {
   return ".....";
}

Then you can reduce your if statement to the following:

if (countryMap[CountryName]) {
   PhoneTemp = countryMap[CountryName](PhoneTemp)
}

You can make an array or structure with countries and the phone prefix.

var Countries = ['India', 'France', 'Spain'];
var Prefixes = [91, 32, 34];

And with it you can save all if-else statements just calling the correct key in array.

Create a dictionary of country converters.

PhoneCountryConverters["India"] = function(PhoneTemp) { return  "+91 " + PhoneTemp.substr(0, 4) + " " + PhoneTemp.substr(4, 6);}

usage:

PhoneTemp = PhoneCountryConverters[Country[0].name](PhoneTemp);

PhoneCountryConverters will have an entry for each country, and you eliminate if statements altogether.

Hi brother you can use two arrays like this :

var CountriesPrefix = {'usa': '+1','India': '+2', 'morocco': '+212'};
var Countries = ['usa', 'India', 'morocco'];
var CountryName='usa';

if($.inArray(CountryName, countries)==0){ //The country is in array
    var PhoneTemp = countries_prefix[CountryName];
}

Using associative array here will reduce the pain of indexs between arrays by using the keys (the keys here are the Countries names).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM