我希望使用 Lodash 优化以下代码。我在网上寻找解决方案,但找不到任何相关内容。有人可以帮忙吗?
if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
if (form && form.application && typeof form.application.disclosureAccepted !== 'undefined' && form.application.disclosureAccepted !== null && !form.application.disclosureAccepted) {
return $q.when(response.data.content);
}
}
最佳答案
if (isPage && isPageType === constants.keys.isDisclosureSubmitted) {
const discAcc = _.get(form, ['application', 'disclosureAccepted'], true);
if (!_.isNil(discAcc) && !disAcc) {
return $q.when(response.data.content);
}
}
基本上,使用 _.get,您不必担心检查 undefined 属性,因为在那种情况下它只会返回 undefined 而不会抛出错误。 _.isNil 检查值是否为 null 或 undefined,然后您要确保该值仍然为 false。
我的意思是,我不确定 lodash 在这种情况下是否“优化”了,因为这些函数调用实际上会减慢它的速度,但它的可读性稍微好一些。就像评论一样,我不确定你为什么需要如此具体;你可以只使用 _.get(form, ['application', 'disclosureAccepted']) == false,我认为我反对使用不严格的等价。
关于javascript - 想使用 Lodash 缩短我的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301506/