首页 > 解决方案 > for ... 在 if 语句之后的语句中

问题描述

我对 js/ts 有点陌生,最近看到了一些看起来像这样的代码:

if (m.attributes) for (const aName in m.attributes) {
...
    }

我希望if验证m.attributes不是错误的(即它不是 null | undefined),然后for语句基本上循环了 m.attributes.

有人可以解释为什么该for声明不在它自己的范围内吗?我希望语法看起来更像这样:

if (m.attributes){
 for (const aName in m.attributes) {
  ...
    }
  }

标签: javascripttypescript

解决方案


如果语句后面只有一个语句,则花括号是多余的if。话虽如此,这:

if (m.attributes) for (const aName in m.attributes) {
     ...
    }

虽然完全有效,但不是一段写得很好的代码。通常,为了增加可读性,人们会这样写:

if (m.attributes)
   for (const aName in m.attributes) {
     ...
    }

推荐阅读