不要在 JavaScript 中使用 If-Else 和 Switch,使用对象字面量_字符串

原文 | https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

翻译 | 小爱


在 JavaScript 中编写复杂的条件总是有可能创建一些非常混乱的代码。一长串 if/else 语句或 switch 案例会很快变得臃肿。

当有多个条件时,我发现对象字面量是构建代码的最易读的方式。让我们来看看它们是如何工作的。

例如,假设我们有一个函数,它接受一个押韵的短语并返回其含义。使用 if/else 语句,它看起来像这样:

function getTranslation(rhyme) {
if (rhyme.toLowerCase() === "apples and pears") {
return "Stairs";
} else if (rhyme.toLowerCase() === "hampstead heath") {
return "Teeth";
} else if (rhyme.toLowerCase() === "loaf of bread") {
return "Head";
} else if (rhyme.toLowerCase() === "pork pies") {
return "Lies";
} else if (rhyme.toLowerCase() === "whistle and flute") {
return "Suit";
}


return "Rhyme not found";
}

这不是很好。它不仅可读性差,而且我们还为每个语句重复 toLowerCase()。

我们可以通过在函数的开头将小写分配给一个变量来避免这种重复,或者使用 switch 语句,如下所示:

function getTranslation(rhyme) {
switch (rhyme.toLowerCase()) {
case "apples and pears":
return "Stairs";
case "hampstead heath":
return "Teeth";
case "loaf of bread":
return "Head";
case "pork pies":
return "Lies";
case "whistle and flute":
return "Suit";
default:
return "Rhyme not found";
}
}

我们现在只调用 toLowerCase() 一次,但这仍然没有什么可读性。switch 语句也容易出错。

在这种情况下,我们只是返回一个值,但是当你具有更复杂的功能时,很容易错过 break 语句并引入错误。

替代方案

你可以使用对象以更简洁的方式实现与上述相同的功能。让我们看一个例子:

function getTranslationMap(rhyme) {
const rhymes = {
"apples and pears": "Stairs",
"hampstead heath": "Teeth",
"loaf of bread": "Head",
"pork pies": "Lies",
"whistle and flute": "Suit",
};


return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}

我们有一个对象,其中键是条件,值是响应。然后我们可以使用方括号符号从传入的韵中选择对象的正确值。

第 10 行的最后一部分(?? “Rhyme not found”)使用无效合并来分配默认响应。这意味着如果 rhymes[rhyme.toLowercase()] 为 null 或未定义(但不是 false 或 0 ),则返回默认字符串“Rhyme not found”。这很重要,因为我们可能合法地希望从我们的条件中返回 false 或 0。例如:

function stringToBool(str) {
const boolStrings = {
"true": true,
"false": false,
};


return boolStrings[str] ?? "String is not a boolean value";
}

这是一个非常人为的示例,但希望它说明了无效合并如何帮助避免引入错误!

更复杂的逻辑

有时你可能需要在你的条件中执行一些更复杂的逻辑。为此,你可以将函数作为值传递给对象键并执行响应:

function calculate(num1, num2, action) {
const actions = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b,
};


return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}

我们正在选择我们想要做的计算并执行响应,传递两个数字。你可以使用可选链接(最后一行代码中的 ?.)来仅执行已定义的响应。否则,将使用默认的返回字符串。

结论

编写条件始终是一种品味问题,某些情况将需要不同的方法。但是,我发现当我有几个条件要检查时,对象文字是最易读和最可维护的方式。

我很想听听你的想法,或者你是否有与上述方法不同的方法!

感谢你的阅读。

不要在 JavaScript 中使用 If-Else 和 Switch,使用对象字面量_字符串_02



不要在 JavaScript 中使用 If-Else 和 Switch,使用对象字面量_字符串_03