我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。

在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?

我这么问,因为似乎每个人都这么做。


当前回答

我目前正在做一个迷你器。即使是现在,我也要检查两个大脚本。通过实验,我发现: 如果花括号不包括';','return','for','if','else','while',' function',则可以删除后面的花括号。不考虑换行。

function a(b){if(c){d}else{e}} //ok  
function a(b){if(c)d;else e}   //ok

当然,如果后面没有其他的结束大括号,则需要用分号替换结束大括号。

函数不能以逗号结尾。

var a,b=function()c;  //ok *but not in Chrome
var b=function()c,a;  //error  

在Chrome和FF上测试。

其他回答

大括号是不必要的.....但无论如何都要加进去

....why should you add braces in if statements if they are not necessary? Because there's a chance that it could cause confusion. If you're dealing with a project with multiple people, from different frameworks and languages, being explicit reduces the chances of errors cropping up by folks misreading each other's code. Coding is hard enough as it is without introducing confusion. But if you are the sole developer, and you prefer that coding style, then by all means, it is perfectly valid syntax.

作为一个普遍的哲学:避免写代码,但如果你必须写,那么让它明确。

if (true){console.log("always runs");}

if (true) console.log("always runs too, but what is to be gained from the ambiguity?");
    console.log("this always runs even though it is indented, but would you expect it to?")

^声明:这是个人观点-意见可能会有所不同。请咨询您的CTO以获得个性化的编码建议。如果编码头痛持续,请咨询医生。

这是一个风格问题,但花括号有助于防止可能的悬空。

语句的开始缩进级别应该等于它上面的开大括号的数量。(不包括引号或注释大括号或预处理器指令中的大括号)

否则,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 (x)
    return y;
    always();

当然,这也是为什么人们可能会使用linter..

我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。

无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。

截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。

function foo()
   return bar;