我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
不直接回答问题,但下面是关于一行中的if条件的简短语法
Ex:
var i=true;
if(i){
dosomething();
}
可以这样写:
var i=true;
i && dosomething();
其他回答
总是发现
if(valid) return;
对我的眼睛来说比
if(valid) {
return;
}
还有条件的,比如
(valid) ? ifTrue() : ifFalse();
(我个人的观点)是否更容易阅读
if(valid) {
ifTrue();
} else {
ifFalse();
}
但我想这归结于编码风格
不直接回答问题,但下面是关于一行中的if条件的简短语法
Ex:
var i=true;
if(i){
dosomething();
}
可以这样写:
var i=true;
i && dosomething();
我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
有一种方法可以实现多行非花括号if语句。(哇,多英语啊..)但是有点乏味:
if(true)
funcName();
else
return null;
function funcName(){
//Do Stuff Here...
}
No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement. So it may be difficult to know whether the code inside the if statement ran without altering the code (some kind of logging/output statements). This is particularly a problem when using commas to add multiple lines of execution. Without adding specific logging, it may be difficult to see what actually ran, or where a particular problem is. My advice is to always use curly braces.