javascript - 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) {
...
}
}
解决方案
如果语句后面只有一个语句,则花括号是多余的if
。话虽如此,这:
if (m.attributes) for (const aName in m.attributes) {
...
}
虽然完全有效,但不是一段写得很好的代码。通常,为了增加可读性,人们会这样写:
if (m.attributes)
for (const aName in m.attributes) {
...
}
推荐阅读
- python - “系列”对象没有属性“values_counts”
- php - Zend HTML 链接到 $baseUrl 上面的文件
- python - 如何让 VS 代码与 Pybuilder python 项目一起使用?
- javascript - $.ajax 自动完成在 jquery 的 ie 11 中不起作用?
- regex - 替换标签名称,同时保持其余部分不变
- javascript - IBM Mobile First 7.1 - 如何在 IBM MFP 7.1 中添加适用于 Android 和 iOS 的 Maps SDK
- facebook - facebook客户聊天信使定位
- regex - 正则表达式测试数学表达式
- java - 从 double 和 long 转换为 int 的细节
- c# - C# 在文本框上搜索复选框但不记得选中或将记录复制两次到复选框 C#