如何使用Lodash简化嵌套if条件判断语句?
用Lodash简化你的嵌套条件判断
嘿,我来帮你把这段嵌套的条件代码用Lodash优化得更简洁易读!
先看看你原来的代码,核心逻辑是:当页面状态符合要求,并且form.application.disclosureAccepted存在(不是undefined或null)且为假值时,返回指定的Promise。我们可以用Lodash的工具函数来消除冗余的存在性检查,同时简化嵌套结构。
优化方案1:保持原逻辑(支持所有非undefined/null的假值)
if (isPage && isPageType === constants.keys.isDisclosureSubmitted) { // 用_.get安全获取嵌套属性,避免路径不存在报错 const disclosureAccepted = _.get(form, 'application.disclosureAccepted'); // 用!= null替代冗长的undefined/null判断,效果完全等价 if (disclosureAccepted != null && !disclosureAccepted) { return $q.when(response.data.content); } }
优化方案2:更紧凑的合并写法
如果想让代码更简洁,可以把内层条件直接整合到外层判断中:
if ( isPage && isPageType === constants.keys.isDisclosureSubmitted && _.get(form, 'application.disclosureAccepted') != null && !_.get(form, 'application.disclosureAccepted') ) { return $q.when(response.data.content); }
额外说明:如果仅需判断布尔值false
如果你实际需求是仅当disclosureAccepted严格等于布尔值false时触发(而不是0、空字符串这类假值),代码可以进一步简化:
if ( isPage && isPageType === constants.keys.isDisclosureSubmitted && _.get(form, 'application.disclosureAccepted') === false ) { return $q.when(response.data.content); }
这里_.get在路径不存在时会返回undefined,而undefined === false不成立,正好自动排除了undefined和null的情况,完美匹配你原代码中对这两个值的过滤逻辑。
优化点总结
_.get():安全访问嵌套属性,避免因form或application不存在而抛出Cannot read property 'xxx' of undefined错误。!= null:等价于typeof x !== 'undefined' && x !== null,大幅简化存在性判断的代码。- 消除嵌套层级:把分散的条件整合,让逻辑流程更直观。
内容的提问来源于stack exchange,提问作者MeSa
相关产品推荐
相关产品推荐

