如何减少此 if 语句检查 JavaScript

How to reduce this if statement check in JavaScript

如何在 JavaScript

中减少这个 if 语句
if(obj.attributes && obj.attributes.email === 'test@test.com') { ... }

您可以使用 Array.reduce() 创建可重复使用的 get 函数。函数参数是路径、对象和默认值(默认 defaultValueundefined)。它将迭代路径,并尝试提取值,如果失败,它将 return defaultValue:

const get = (path, obj, defaultValue) => obj ? 
  path.reduce((r, k) => r && typeof r === 'object' ? r[k] : defaultValue, obj) 
  : 
  defaultValue;

if(get(['attributes', 'email'], null) === 'test@test.com') { console.log(1) }
if(get(['attributes', 'email'], {}) === 'test@test.com') { console.log(2) }
if(get(['attributes', 'email'], { attributes: {} }) === 'test@test.com') { console.log(3) }
if(get(['attributes', 'email'], { attributes: { email: 'test@test.com' } }) === 'test@test.com') { console.log(4) }

有一个名为 "Optional Chaining for JavaScript" 的 TC39 阶段提案。如果它将成为语言的一部分,它将添加一个可选的链接运算符 - ?。现在如果 attributes 不存在,它将 return undefined.

示例: obj.attributes?.email

今天可以通过 babel plugin 使用。

这一行本身很清楚,但是如果你正在寻找一种方法来减少 && 运算符,你总是可以把东西放在比较之外,例如。

var attributes = obj.attributes || {};
if ( attributes.email === 'test@test.com' ) {
}

如果您需要进行多次检查而不是一次检查,这是有道理的,但是如果是一次比较,您已经拥有的代码似乎没问题,因为您要确保之前定义了 attributes访问 undefined 属性.

另一方面,如果你支持 ES 2015,你可以破坏像这样的东西:

const { attributes = {} } = obj;
if ( attributes.email === 'test@test.com' ) {
}