JavaScript 中多个 if else 语句的替代方案?



我有一个输入,其中包含一个包含 8 个项目的下拉列表。根据用户选择的选项,我想将其输入的值更改为不同的字符串值。为了做到这一点,我使用了大量的if else语句,这使得它看起来非常笨重,如果可能的话,我想压缩它。我有以下代码:

if (inputFive == "Corporation"){
inputFive = "534"
} else if (inputFive == "LLC"){
inputFive = "535"
} else if(inputFive == "LLP"){
inputFive = "536"
} else if(inputFive == "Partnership"){
inputFive = "537"
} else if(inputFive == "Sole Proprietorship"){
inputFive = "538"
} else if(inputFive == "Limited Partnership"){
inputFive = "539"
} else {
inputFive = "540"
}

如您所见,这看起来有点老派,我想看看是否有更好/更简单的方法来实现这一点。如果可能的话,只是希望压缩此代码。我相信它们可能是通过分配键/值对象来创建字典的一种方式,但我不知道如何正确执行此操作......所有选项/提示将不胜感激!

您可以将对象用作映射:

function getCode(input) {
var inputMap = {
"Corporation": "534",
"LLC": "535",
"LLP": "536",
"Partnership": "537",
"Sole Proprietorship": "538",
"Limited Partnership": "539"
};
var defaultCode = "540";

return inputMap[input] || defaultCode;
}
console.log(getCode("LLP"));
console.log(getCode("Lorem Ipsum"));

你的直觉完全正确。你会这样做:

var mapping = {
"Corporation": "534",
"LLC": "535",
...
"default": "540"
}
inputFive = mapping[inputFive] || mapping["default"]

使用switch语句,这在要针对多个可能值检查单个变量的情况更好:

switch (inputFive) {
case "Corporation" :
inputFive = "534";
break;
case "LLC":
inputFive = "535";
break;
case "LLP":
inputFive = "536";
break;
case "Partnership":
inputFive = "537";
break;
case "Sole Proprietorship":
inputFive = "538";
break;
case "Limited Partnership":
inputFive = "539";
break;
default:
inputFive = "540";
break;
}

// just another way but not faster than others at all
// so then order is important 
var inputMap = [
"Corporation","LLC","LLP",
"Partnership","Sole Proprietorship",
"Limited Partnership"
];
var res = inputMap.indexOf(input);
res = res > -1 ? 534 + res : 540;

你可能想要某种数组。

businessTypes = [];
businessTypes["Corporation"] = 534;
businessTypes["LLC"] = 535;
businessTypes["LLP"] = 536;
businessTypes["Partnership"] = 537;
businessTypes["Sole Proprietorship"] = 538;
businessTypes["Limited Partnership"] = 539;

然后你可以用类似的东西来引用它:

businessId = businessTypes[inputFive] ? businessTypes[inputFive] : 540;
console.log(businessId);

你也可以把它分解成一个函数:

function getBusinessId(type) {
businessTypes = [];
businessTypes["Corporation"] = 534;
businessTypes["LLC"] = 535;
businessTypes["LLP"] = 536;
businessTypes["Partnership"] = 537;
businessTypes["Sole Proprietorship"] = 538;
businessTypes["Limited Partnership"] = 539;
return businessTypes[type] ? businessTypes[type] : 540;
}
var businessId = getBusinessId("LLC");
console.log(businessId); // 535

最新更新