你還在使用 If-Else 和 Switch 嗎?建議嘗試下更好用的對象字面量

原文 | https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0
翻譯 | 小愛
在 JavaScript 中編寫復(fù)雜的條件總是有可能創(chuàng)建一些非?;靵y的代碼。一長串 if/else 語句或 switch 案例會(huì)很快變得臃腫。
當(dāng)有多個(gè)條件時(shí),我發(fā)現(xiàn)對象字面量是構(gòu)建代碼的最易讀的方式。讓我們來看看它們是如何工作的。
例如,假設(shè)我們有一個(gè)函數(shù),它接受一個(gè)押韻的短語并返回其含義。使用 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";}
這不是很好。它不僅可讀性差,而且我們還為每個(gè)語句重復(fù) toLowerCase()。
我們可以通過在函數(shù)的開頭將小寫分配給一個(gè)變量來避免這種重復(fù),或者使用 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 語句也容易出錯(cuò)。
在這種情況下,我們只是返回一個(gè)值,但是當(dāng)你具有更復(fù)雜的功能時(shí),很容易錯(cuò)過 break 語句并引入錯(cuò)誤。
替代方案
你可以使用對象以更簡潔的方式實(shí)現(xiàn)與上述相同的功能。讓我們看一個(gè)例子:
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";}
我們有一個(gè)對象,其中鍵是條件,值是響應(yīng)。然后我們可以使用方括號(hào)符號(hào)從傳入的韻中選擇對象的正確值。
第 10 行的最后一部分(?? “Rhyme not found”)使用無效合并來分配默認(rèn)響應(yīng)。這意味著如果 rhymes[rhyme.toLowercase()] 為 null 或未定義(但不是 false 或 0 ),則返回默認(rèn)字符串“Rhyme not found”。這很重要,因?yàn)槲覀兛赡芎戏ǖ叵M麖奈覀兊臈l件中返回 false 或 0。例如:
function stringToBool(str) {const boolStrings = {"true": true,"false": false,};return boolStrings[str] ?? "String is not a boolean value";}
這是一個(gè)非常人為的示例,但希望它說明了無效合并如何幫助避免引入錯(cuò)誤!
更復(fù)雜的邏輯
有時(shí)你可能需要在你的條件中執(zhí)行一些更復(fù)雜的邏輯。為此,你可以將函數(shù)作為值傳遞給對象鍵并執(zhí)行響應(yīng):
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";}
學(xué)習(xí)更多技能
請點(diǎn)擊下方公眾號(hào)
![]()
