不要在 JavaScript 中使用 If-Else 和 Switch,使用對象字面量

原文 | https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0
翻譯 | 小愛
在 JavaScript 中編寫復雜的條件總是有可能創(chuàng)建一些非常混亂的代碼。一長串 if/else 語句或 switch 案例會很快變得臃腫。
當有多個條件時,我發(fā)現(xiàn)對象字面量是構建代碼的最易讀的方式。讓我們來看看它們是如何工作的。
例如,假設我們有一個函數(shù),它接受一個押韻的短語并返回其含義。使用 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()。
我們可以通過在函數(shù)的開頭將小寫分配給一個變量來避免這種重復,或者使用 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";}}
我們現(xiàn)在只調(diào)用 toLowerCase() 一次,但這仍然沒有什么可讀性。switch 語句也容易出錯。
在這種情況下,我們只是返回一個值,但是當你具有更復雜的功能時,很容易錯過 break 語句并引入錯誤。
替代方案
你可以使用對象以更簡潔的方式實現(xiàn)與上述相同的功能。讓我們看一個例子:
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";}
這是一個非常人為的示例,但希望它說明了無效合并如何幫助避免引入錯誤!
更復雜的邏輯
有時你可能需要在你的條件中執(zhí)行一些更復雜的邏輯。為此,你可以將函數(shù)作為值傳遞給對象鍵并執(zhí)行響應:
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";}
學習更多技能
請點擊下方公眾號
![]()

