重构 JS 函数中 if/else 语句的 5 种方法
1.默认参数
2. 或运算符
3. 空值合并
4. 可选链式调用
5. 无其他返回值和保护条款
在这篇博文中,我将介绍 5 种简化代码、去除不必要if-else
语句的方法。我将讨论以下内容:
- 默认参数,
- 或(||)运算符,
- 零值合并,
- 可选链式调用,
- 无其他回报和保护条款
1.默认参数
您知道当您使用不一致的 API 并且您的代码由于某些值而中断时的那种感觉undefined
吗?
let sumFunctionThatMayBreak = (a, b, inconsistentParameter) => a+b+inconsistentParameter
sumFunctionThatMayBreak(1,39,2) // => 42
sumFunctionThatMayBreak(2,40, undefined) // => NaN
我发现对于许多人来说,解决这个问题的本能方法是添加一条if/else
语句:
let sumFunctionWithIf = (a, b, inconsistentParameter) => {
if (inconsistentParameter === undefined){
return a+b
} else {
return a+b+inconsistentParameter
}
}
sumFunctionWithIf(1,39,2) // => 42
sumFunctionWithIf(2,40, undefined) // => 42
if/else
但是,您可以通过实现默认参数来简化上述函数并消除逻辑:
let simplifiedSumFunction = (a, b, inconsistentParameter = 0) => a+b+inconsistentParameter
simplifiedSumFunction(1, 39, 2) // => 42
simplifiedSumFunction(2, 40, undefined) // => 42
2. 或运算符
上述问题并不总是可以通过默认参数解决。有时,您可能需要使用逻辑if-else
,尤其是在尝试构建条件渲染功能时。在这种情况下,上述问题通常可以通过以下方式解决:
let sumFunctionWithIf = (a, b, inconsistentParameter) => {
if (inconsistentParameter === undefined || inconsistentParameter === null || inconsistentParameter === false){
return a+b
} else {
return a+b+inconsistentParameter
}
}
sumFunctionWithIf(1, 39, 2) // => 42
sumFunctionWithIf(2, 40, undefined) // => 42
sumFunctionWithIf(2, 40, null) // => 42
sumFunctionWithIf(2, 40, false) // => 42
sumFunctionWithIf(2, 40, 0) // => 42
/// 🚨🚨🚨 but:
sumFunctionWithIf(1, 39, '') // => "40"
或者这样:
let sumFunctionWithTernary = (a, b, inconsistentParameter) => {
inconsistentParameter = !!inconsistentParameter ? inconsistentParameter : 0
return a+b+inconsistentParameter
}
sumFunctionWithTernary(1,39,2) // => 42
sumFunctionWithTernary(2, 40, undefined) // => 42
sumFunctionWithTernary(2, 40, null) // => 42
sumFunctionWithTernary(2, 40, false) // => 42
sumFunctionWithTernary(1, 39, '') // => 42
sumFunctionWithTernary(2, 40, 0) // => 42
但是,您可以使用OR ( ||
) 运算符进一步简化它。该||
运算符的工作方式如下:
falsey
当左侧是一个值时,它返回右侧;- 如果是,则返回左侧
truthy
。
解决方案可能如下所示:
let sumFunctionWithOr = (a, b, inconsistentParameter) => {
inconsistentParameter = inconsistentParameter || 0
return a+b+inconsistentParameter
}
sumFunctionWithOr(1,39,2) // => 42
sumFunctionWithOr(2,40, undefined) // => 42
sumFunctionWithOr(2,40, null) // => 42
sumFunctionWithOr(2,40, false) // => 42
sumFunctionWithOr(2,40, '') // => 42
sumFunctionWithOr(2, 40, 0) // => 42
3. 空值合并
然而,有时你确实希望将0
或保留''
为有效参数,而无法使用||
运算符来实现这一点,如上例所示。幸运的是,从今年开始,JavaScript 允许我们使用??
(空值合并) 运算符,该运算符仅当左侧为或时才返回右侧null
undefined
。这意味着,如果你的参数是0
或''
,它将被如此处理。让我们看看实际效果:
let sumFunctionWithNullish = (a, b, inconsistentParameter) => {
inconsistentParameter = inconsistentParameter ?? 0.424242
return a+b+inconsistentParameter
}
sumFunctionWithNullish(2, 40, undefined) // => 42.424242
sumFunctionWithNullish(2, 40, null) // => 42.424242
/// 🚨🚨🚨 but:
sumFunctionWithNullish(1, 39, 2) // => 42
sumFunctionWithNullish(2, 40, false) // => 42
sumFunctionWithNullish(2, 40, '') // => "42"
sumFunctionWithNullish(2, 40, 0) // => 42
4. 可选链式调用
最后,当处理不一致的数据结构时,确保每个对象都具有相同的键是一件痛苦的事情。参见此处:
let functionThatBreaks = (object) => {
return object.name.firstName
}
functionThatBreaks({name: {firstName: "Sylwia", lasName: "Vargas"}, id:1}) // ✅ "Sylwia"
functionThatBreaks({id:2}) // 🚨 Uncaught TypeError: Cannot read property 'firstName' of undefined 🚨
发生这种情况是因为object.name
存在undefined
,所以我们无法调用firstName
它。
许多人通过以下方式处理这种情况:
let functionWithIf = (object) => {
if (object && object.name && object.name.firstName) {
return object.name.firstName
}
}
functionWithIf({name: {firstName: "Sylwia", lasName: "Vargas"}, id:1) // "Sylwia"
functionWithIf({name: {lasName: "Vargas"}, id:2}) // undefined
functionWithIf({id:3}) // undefined
functionWithIf() // undefined
但是,您可以使用新的 ECMA2020 JS 功能简化上述操作:optional chaining
。可选链接在每一步检查返回值是否为undefined
,如果是,则仅返回该值而不是引发错误。
let functionWithChaining = (object) => object?.name?.firstName
functionWithChaining({name: {firstName: "Sylwia", lasName: "Vargas"}, id:1}) // "Sylwia"
functionWithChaining({name: {lasName: "Vargas"}, id:2}) // undefined
functionWithChaining({id:3}) // undefined
functionWithChaining() // undefined
5. 无其他返回值和保护条款
解决if/else
语句冗长(尤其是嵌套语句)的最后一个方法是使用no-else-return 语句和guard clauses
。假设我们有这个函数:
let nestedIfElseHell = (str) => {
if (typeof str == "string"){
if (str.length > 1) {
return str.slice(0,-1)
} else {
return null
}
} else {
return null
}
}
nestedIfElseHell("") // => null
nestedIfElseHell("h") // => null
nestedIfElseHell("hello!") // => "hello"
✨ 别无回报
现在,我们可以用no-else-return
语句简化这个函数,因为我们返回的只是null
:
let noElseReturns = (str) => {
if (typeof str == "string"){
if (str.length > 1) {
return str.slice(0,-1)
}
}
return null
}
noElseReturns("") // => null
noElseReturns("h") // => null
noElseReturns("hello!") // => "hello"
该语句的好处no-else-return
是,如果条件不满足,函数将结束执行if-else
并跳转到下一行。你甚至可以省略最后一行(return null
),这样返回的结果就是undefined
。
嘘:实际上,我在前面的例子中使用了 no-else-return 函数👀
✨ 保护条款
现在我们可以更进一步,设置可以更早结束代码执行的保护措施:
let guardClauseFun = (str) => {
// ✅ first guard: check the type
if (typeof str !== "string") return null
// ✅ second guard: check for the length
if (str.length <= 3) console.warn("your string should be at least 3 characters long and its length is", str.length)
// otherwise:
return str.slice(0,-1)
}
guardClauseFun(5) // => null
guardClauseFun("h") // => undefined with a warning
guardClauseFun("hello!") // => "hello"
您使用什么技巧来避免笨重的 if/else 语句?
✨✨✨ 如果您对 OOP JS 感到满意,一定要查看Maxi Contieri 的这篇精彩博客文章!
文章来源:https://dev.to/sylwiavargas/5-ways-to-refactor-if-else-statements-in-js-functions-208e