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

use*_*442 1 javascript conditional dictionary if-statement

我有一个输入,其中包含8个项目的下拉列表.根据用户选择的选项,我想将其输入值更改为不同的字符串值.为了做到这一点,我使用一吨,如果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"
}
Run Code Online (Sandbox Code Playgroud)

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

Asa*_*din 5

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

var mapping = {
    "Corporation": "534",
    "LLC": "535",
    ...
    "default": "540"
}
inputFive = mapping[inputFive] || mapping["default"]
Run Code Online (Sandbox Code Playgroud)


Alb*_*res 5

您可以将对象用作地图:

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"));
Run Code Online (Sandbox Code Playgroud)