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

Alternative to multiple if else statements in JavaScript?

我有一个包含 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"
}

如您所见,这看起来有点过时,我想看看是否有 better/simpler 方法来实现这一点。如果可能的话,只是想压缩这段代码。我相信他们可能是通过分配 key/value 对象来创建字典的一种方法,但我不知道如何正确地做到这一点......所有 options/hints 将不胜感激!

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

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

您可以将对象用作地图:

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"));

您可能需要某种数组。

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

   // 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;