我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
当前回答
在一行语句上使用花括号是没有编程理由的。
这只取决于程序员的偏好和可读性。
您的代码不会因此而崩溃。
其他回答
如果你这样做,请这样写:
if(a===1) if(b===2) alert(a);
alert(b);
语句的开始缩进级别应该等于它上面的开大括号的数量。(不包括引号或注释大括号或预处理器指令中的大括号)
否则,K&R将是很好的缩进样式。为了修复它们的风格,我建议在一行中放置简短的if语句。
if (foo) bar(); // I like this. It's also consistent with Python FWIW
而不是
if (foo)
bar(); // not so good
如果我正在编写一个编辑器,我会让它的自动格式按钮将bar吸到与foo相同的行,并且如果你在bar之前按下return,我会让它在bar周围插入括号:
if (foo) {
bar(); // better
}
然后,在if语句的主体中在bar的上方或下方添加新语句就很容易且一致了
if (foo) {
bar(); // consistent
baz(); // easy to read and maintain
}
以下是推荐的原因
假设我写
if(someVal)
alert("True");
然后下一个开发人员说,“哦,我需要做一些其他的事情”,所以他们写了下来
if(someVal)
alert("True");
alert("AlsoTrue");
现在你可以看到"AlsoTrue"总是为真,因为第一个开发人员没有使用大括号。
有一种方法可以实现多行非花括号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.