简体   繁体   English

减少if else语句的数量?

[英]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. 我有一些JavaScript,当用户在电话字段中输入10位数时,它会检查国家/地区字段是否已填充,以便为其分配国家/地区代码。 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? 如果我以这种方式做到最终会导致100+其他,如果有更好的方式吗?

You can use switch or you can use Jquery $.inArray(val, array) 你可以使用switch或者你可以使用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语句减少到以下内容:

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. 有了它,你可以保存所有if-else语句只是在数组中调用正确的键。

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. PhoneCountryConverters将为每个国家/地区提供一个条目,您可以完全删除if语句。

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). 在这里使用关联数组将通过使用键减少数组之间的索引的痛苦(这里的键是国家名称)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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