我有一个包含 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"
}
如您所见,这看起来有点过时,我想看看是否有更好/更简单的方法来实现这一点。如果可能的话,只是想压缩这段代码。我相信他们可能是通过分配键/值对象来创建字典的一种方法,但我不知道如何正确地做到这一点......所有选项/提示将不胜感激!
最佳答案
您可以将对象用作 map :
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"));
关于javascript - 替代 JavaScript 中的多个 if else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44977953/