我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
我曾经听说,在一行语句中使用花括号对JavaScript是有害的。我不记得推理了,谷歌搜索也没有多大帮助。
在JavaScript中,把所有语句都用大括号括起来是一个好主意吗?
我这么问,因为似乎每个人都这么做。
No
但他们是被推荐的。如果你要展开你的陈述,你会需要它们。
这是完全有效的
if (cond)
alert("Condition met!")
else
alert("Condition not met!")
然而,强烈建议您总是使用大括号,因为如果您(或其他人)展开语句,就会需要它。
在所有带有括号的C语法风格语言中都遵循同样的做法。C, c++, Java,甚至PHP都支持不带括号的一行语句。你必须意识到你只保存了两个角色,有些人的支撑风格甚至连一行都没有保存。我更喜欢全括号的风格(像下面这样),所以它往往有点长。这种权衡很好地满足了代码可读性非常清晰的事实。
if (cond)
{
alert("Condition met!")
}
else
{
alert("Condition not met!")
}
以下是推荐的原因
假设我写
if(someVal)
alert("True");
然后下一个开发人员说,“哦,我需要做一些其他的事情”,所以他们写了下来
if(someVal)
alert("True");
alert("AlsoTrue");
现在你可以看到"AlsoTrue"总是为真,因为第一个开发人员没有使用大括号。
有一个可读性方面-当你有复合语句时,它可能会非常混乱。缩进有帮助,但对编译器/解释器没有任何意义。
var a;
var b;
var c;
//Indenting is clear
if (a===true)
alert(a); //Only on IF
alert(b); //Always
//Indenting is bad
if (a===true)
alert(a); //Only on IF
alert(b); //Always but expected?
//Nested indenting is clear
if (a===true)
if (b===true)
alert(a); //Only on if-if
alert (b); //Always
//Nested indenting is misleading
if (a===true)
if (b===true)
alert(a); //Only on if-if
alert (b); //Always but expected as part of first if?
//Compound line is misleading
//b will always alert, but suggests it's part of if
if (a===true) alert(a);alert(b);
else alert(c); //Error, else isn't attached
然后是可扩展性方面:
//Problematic
if (a===true)
alert(a);
alert(b); //We're assuming this will happen with the if but it'll happen always
else //This else is not connected to an if anymore - error
alert(c);
//Obvious
if (a===true) {
alert(a); //on if
alert(b); //on if
} else {
alert(c); //on !if
}
这种想法是这样的,如果你总是有括号,那么你就知道在这个块中插入其他语句。
除了@Josh K提到的原因(这也适用于Java, C等),JavaScript中的一个特殊问题是自动分号插入。维基百科的例子如下:
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
因此,如果像这样使用,也可能会产生意想不到的结果:
if (x)
return
a + b;
写也没好到哪里去
if (x) {
return
a + b;
}
但也许这里的错误更容易检测(?)
不存在可维护性问题!
你们所有人的问题就是到处都用分号。多个语句不需要花括号。如果你想添加一个语句,只需使用逗号。
if (a > 1)
alert("foo"),
alert("bar"),
alert("lorem"),
alert("ipsum");
else
alert("blah");
这是有效的代码,将像您期望的那样运行!
这个问题问的是一行中的语句。然而,提供的许多示例说明了不要基于多行语句省略大括号的理由。在一行中不使用括号是完全安全的,如果这是您喜欢的编码风格的话。
例如,问题问这样做是否可以:
if (condition) statement;
它不会问这是否ok:
if (condition)
statement;
我认为去掉括号更可取,因为它使代码更具可读性,语法更少。
我的编码风格是永远不用括号,除非代码是一个块。不要在一行上使用多个语句(用分号分隔)。我发现这很容易阅读和清楚,从来没有“if”语句的范围问题。因此,在单个if条件语句上使用括号需要3行。是这样的:
if (condition) {
statement;
}
使用一行if语句更可取,因为它使用的垂直空间更少,代码更紧凑。
我不会强迫其他人使用这种方法,但它对我来说是有效的,我非常不同意所提供的关于省略括号如何导致编码/范围错误的例子。
有时他们似乎是需要的!我自己都不敢相信,但是昨天我在Firebug会议上(最近的Firefox 22.0)突然想到
if (! my.condition.key)
do something;
执行do something,尽管my。condition。key为true。添加括号:
if (! my.condition.var) {
do something;
}
解决了这个问题。有无数的例子表明,它显然可以在没有括号的情况下工作,但在这种情况下,它肯定没有。
倾向于在一行中放入多个语句的人当然应该总是使用大括号,因为
if (condition)
do something; do something else;
很难找到。
我目前正在做一个迷你器。即使是现在,我也要检查两个大脚本。通过实验,我发现: 如果花括号不包括';','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上测试。
我想指出的是,你也可以把花括号去掉else。正如约翰·瑞西格在这篇文章中看到的。
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
javascript有很多问题。看看JavaScript架构师Douglas Crockford谈论的if语句似乎很好,但return语句可能会引入一个问题。
return
{
ok:false;
}
//silent error (return undefined)
return{
ok:true;
}
//works well in javascript
有一种方法可以实现多行非花括号if语句。(哇,多英语啊..)但是有点乏味:
if(true)
funcName();
else
return null;
function funcName(){
//Do Stuff Here...
}
技术上没有,但是非常推荐!!
忘掉“这是个人偏好”、“代码会正常运行”、“它对我来说工作得很好”、“它更可读”之类的废话。如果你犯了一个错误,这很容易导致非常严重的问题,相信我,当你在编码时很容易犯错误(不相信吗?,看看著名的苹果go to fail漏洞)。
论据:“这是个人偏好”
不,不是的。除非你们是一个人去火星,不然不行。大多数时候会有其他人阅读/修改您的代码。在任何严肃的编码团队中,这都是被推荐的方式,所以这不是一个“个人偏好”。
参数:“代码将运行良好”
意面代码也是如此!这是否意味着可以创建它?
论据:“这对我来说很有效”
在我的职业生涯中,我见过很多因为这个问题而产生的bug。你可能不记得有多少次你注释掉了“DoSomething()”,并对为什么要调用“SomethingElse()”感到困惑:
if (condition)
DoSomething();
SomethingElse();
或者添加了'SomethingMore'并且没有注意到它将不会被调用(即使缩进暗示相反):
if (condition)
DoSomething();
SomethingMore();
这是我在现实生活中遇到的一个例子。有人想要关闭所有日志,所以他们运行find&replace "console.log" => //"console.log":
if (condition)
console.log("something");
SomethingElse();
看到问题了吗?
即使你认为,“这些都是微不足道的,我永远不会这么做”;记住,总会有一个团队成员的编程技能不如你(希望你不是团队中最差的!)
参数:“这更有可读性”
如果说我学过编程,那就是简单的事情很快就会变得非常复杂。这是很常见的:
if (condition)
DoSomething();
在使用不同的浏览器/环境/用例进行测试或添加新功能后,它会变成以下内容:
if (a != null)
if (condition)
DoSomething();
else
DoSomethingElse();
DoSomethingMore();
else
if (b == null)
alert("error b");
else
alert("error a");
和这个比较:
if (a != null) {
if (condition) {
DoSomething();
}
else {
DoSomethingElse();
DoSomethingMore();
}
} else if (b == null) {
alert("error b");
} else {
alert("error a");
}
PS:在上面的例子中注意到错误的人会得到加分。
我在一个类似的经历中找到了这个答案,所以我决定用我的经历来回答它。
无括号语句在大多数浏览器中都可以工作,然而,我测试了无括号方法实际上在某些浏览器中不起作用。
截至2018年2月26日,该声明在苍白的月亮,但不是谷歌Chrome。
function foo()
return bar;
语句的开始缩进级别应该等于它上面的开大括号的数量。(不包括引号或注释大括号或预处理器指令中的大括号)
否则,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(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();
有很多好的答案,所以我不会重复,除了说我的“规则”时,大括号可以省略:条件'返回'或'抛出'(例如)作为他们的唯一声明。在这种情况下,流控制已经清楚地表明它正在终止:
由于终止流控制,即使是“坏情况”也可以快速识别(并修复)。这个概念/结构“规则”也适用于许多语言。
if (x)
return y;
always();
当然,这也是为什么人们可能会使用linter..
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.
大括号是不必要的.....但无论如何都要加进去
....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以获得个性化的编码建议。如果编码头痛持续,请咨询医生。