我今天注意到,JavaScript对象的循环可以使用较少的大括号来完成.
例如,正常的做事方式:
// The normal way
var foo = {
bar: 1
};
for(var key in foo) {
if(foo.hasOwnProperty(key)) {
console.log(foo[key]); // prints out 1
}
}
Run Code Online (Sandbox Code Playgroud)
替代方案,通过删除额外{ ... },它仍然有效:
// The alternative
var foo = {
bar: 1
};
for(var key in foo) if(foo.hasOwnProperty(key)) { // <-- see :)
console.log(foo[key]); // prints out 1
}
Run Code Online (Sandbox Code Playgroud)
但是,我不太清楚为什么这是可能的.所以我的问题是:什么时候可以省略花括号?我得到了一个说"太宽泛"的downvote所以我试着强调我不是在寻找一百万个用例,简短的答案套装就好了解释了基础知识.
提前致谢!
只要只有一条语句,就可以省略花括号。
for (var x in obj) {
console.log(x);
}
Run Code Online (Sandbox Code Playgroud)
可以变成
for (var x in obj)
console.log(x);
Run Code Online (Sandbox Code Playgroud)
但是如果你有
for (var x in obj) {
console.log(x);
console.log(x);
}
Run Code Online (Sandbox Code Playgroud)
它需要花括号。
这有点不一致。例如,它的工作原理为for,while和if,但不为try或catch。为了保持一致,我始终使用花括号。
在一个if或循环(for,while)之后你可以省略{如果你之后只有一个语句.所以
if (condition)
someFunction();
Run Code Online (Sandbox Code Playgroud)
等于
if (condition) {
someFunction();
}
Run Code Online (Sandbox Code Playgroud)
和
if (condition) a(); b();
Run Code Online (Sandbox Code Playgroud)
等于
if (condition) {
a();
}
b();
Run Code Online (Sandbox Code Playgroud)
你甚至可以嵌套:
if (condition)
while(condition2)
if (condition3)
someFunction();
Run Code Online (Sandbox Code Playgroud)
为了便于阅读,最好(阅读:我更喜欢)总是使用大括号(也不太容易造成编程错误).
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |