【问题标题】:How to reduce this if statement check in JavaScript如何在 JavaScript 中减少这种 if 语句检查
【发布时间】:2019-03-30 15:23:04
【问题描述】:

如何减少 JavaScript 中的 if 语句

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

【问题讨论】:

  • 如果obj.attributes 可能是未定义的,你不能 - 好吧,你可以使用 try/catch,但这可能是更多代码
  • 坦率地说,这对我来说看起来不错,它已经清晰简洁了。虽然你可以使用更短但可以说更糟:if ((obj.attributes || {}).email === "test@test.com") { ... }
  • 那张支票没有问题。一种可能的选择是if((obj.attributes || {email:''}).email === 'test@test.com') { ... },但看起来更糟。
  • 没有简单的方法可以做到这一点。解决方法是存在的,但它们只对更长的链真正值得 - 在这种情况下,我通常这样做的方式无论如何都会很长,而且可能更难阅读。
  • 相关:Null-safe property access (and conditional assignment) in ES6/2015,如果我们有可选的链接,你可以使用obj.attributes?.email === ...

标签: javascript if-statement shorthand


【解决方案1】:

这条线本身很清楚,但是如果您正在寻找一种在内部编写更少 && 运算符的方法,您总是可以将一些东西放在比较之外。

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

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

另一方面,如果您支持 ES 2015,您可以破坏以下内容:

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

【讨论】:

    【解决方案2】:

    您可以使用Array.reduce() 创建可重用的get 函数。函数参数是路径、对象和默认值(默认 defaultValueundefined)。它将迭代路径,并尝试提取值,如果失败,它将返回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 不存在,它将返回undefined

    示例: obj.attributes?.email

    今天可以通过babel plugin使用。

    【讨论】:

      猜你喜欢
      • 2022-12-16
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多