【问题标题】:avoid nested if in javascript [duplicate]避免在javascript中嵌套if [重复]
【发布时间】:2020-09-27 07:52:42
【问题描述】:

我需要检查 auth.runtime.status 是否等于 200,但是 auth.runtime 是不可判断的,在 nodejs 中是否有更优雅的方法来做到这一点

    if (auth.runtime) {
            if (auth.runtime.status == 200 && auth.application.status == 200) 



...

 }
}

有没有更好的写法?

假设我有更多的嵌套 if

【问题讨论】:

  • 您需要在您的问题上添加 else 条件,然后我们可以帮助您
  • 尽可能多地显示,即如果auth.runtimeundefined会发生什么

标签: javascript node.js


【解决方案1】:

您可以使用单个 if 语句来获取 optional chaining operator ?.

if (auth.runtime?.status == 200 && auth.application.status == 200) 

【讨论】:

  • 这假定 OP 使用的任何环境都支持 optional chaining operator,并且目前在 Node.js 中不受支持。
猜你喜欢
  • 2021-04-28
  • 2017-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多