问题描述
我在 JavaScript 中经常使用分号:
I tend to be a prolific user of semicolons in my JavaScript:
var x = 1;
var y = 2;
if (x==y){do something};
我最近注意到我正在查看很多在 if 语句之后没有分号的 JavaScript.然后我突然想到,我什至不知道 JS 中分号的首选语法,经过一些谷歌搜索了解到(相当令人惊讶)除了拆分一行中的语句外,根本不需要分号.
I recently noticed that I was looking at a lot of JavaScript that doesn't have semicolons following if statements. It then occurred to me that I don't even know the preferred syntax for semicolons in JS and after some googling learned (rather surprisingly) that there is no need for semicolons at all aside from splitting statements that are on one line.
那么,问题...人们使用分号的习惯从何而来?它是 JavaScript 出现时使用的某种流行语言的残余吗?只是一般的好习惯?只有我吗?
So, the question...where did this habit of people using semicolons come from? Is it a remnant from some popular language that was in use at the time JavaScript came into play? Just good practice in general? Is it just me?
我可能会坚持下去,没有其他原因,因为在编写 jQuery 链时很容易发现结尾.
I'm probably going to stick with it for no other reason that it's nice when writing jQuery chains to easily spot the end.
更新:
谢谢大家的回答!总而言之,我们在 JS 中看到很多分号甚至不需要的原因来自各种变量:
Thanks for all the answers, everyone! It looks like, to summarize things, the reason we see a lot of semicolons in JS even when not needed comes from various variables:
- 如果不插入分号,旧的 JS 最小化器会产生损坏的代码
- 许多其他语言都在使用它们,因此这是一种遗留下来的习惯
- 有时,分号可以改变逻辑
- 有些人更喜欢使用它们来使代码更具可读性
推荐答案
许多计算机语言使用分号来表示语句的结尾.C、C++ 和 Java 是这方面的流行示例.
Many computer languages use semicolons to denote the end of a statement. C, C++, and Java are popular examples of this.
至于为什么人们使用它们,尽管它们是可选的,但它们提高了代码的可读性.在大多数情况下,这只是出于习惯,但有时您需要在代码中使用分号来消除可能的歧义.总是比抱歉更安全(和一致).
As for why people use them despite them being optional, they improve the readability of your code. In most cases it's simply done out of habit, but occasionally you need semicolons in your code to remove possible ambiguity. It's always better safe (and consistent) than sorry.
这是从 你推荐在 JavaScript 中的每个语句后使用分号?
// define a function
var fn = function () {
//...
} // semicolon missing at this line
// then execute some code inside a closure
(function () {
//...
})();
这将被解释为:
var fn = function () {
//...
}(function () {
//...
})();
此外,分号允许 Javascript 正确打包/缩小.否则所有的语句都会被混为一团.
Additionally, semicolons allow Javascript to be packed/minified properly. Otherwise all the statements will be mushed together into one big mess.
这篇关于为什么 JavaScript 中有这么多分号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!