Javascript:不需要分号的情况?
我正在设置一些数据来执行 AJAX 发布,代码如下所示。
var data = {}
data.someId= 3;
data.anotherId = 4;
这很好用。但为什么我不需要在第一行末尾加分号呢?
I am setting up some data to do an AJAX post and the code looks like this.
var data = {}
data.someId= 3;
data.anotherId = 4;
and this works fine. But why don't I need a semi-colon at the end of the first line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
因为 JavaScript 具有自动分号插入。
我之前错误地将其称为自动分号注入,这是有道理的:P
语言需要它们,但它会预处理您的脚本并尝试猜猜他们应该去哪里。这并不总是有效,正如您在 pst 的评论中看到的那样。
您应该自己定义分号。不要让 JavaScript 猜测。
Because JavaScript has Automatic Semicolon Insertion.
I erroneously called it Automatic Semicolon Injection earlier, which kind of makes sense :P
The language requires them, but it preprocesses your script and tries to guess where they should go. This doesn't always work out, as you can see in pst's comment.
You should just define the semi colons yourself. Don't let JavaScript guess.
它们是
可选
。你不需要这些。https://mislav.net/2010/05/semicolons/
They are
optional
. You don't need any of those.https://mislav.net/2010/05/semicolons/
Javascript 中不需要使用分号来表示一行中的单个语句。
A semi colon for a single statement on a line is not required in Javascript.
JavaScript 实际上不需要分号来确定语句的结束。如果没有分号,它将使用一个新行作为语句的结尾。唯一需要使用分号的情况是,如果您想将两个语句一个接一个地放在同一行上。
话虽如此,最好的做法是始终以分号结束语句
避免混淆并避免难以发现的错误。
JavaScript actually doesn't require semicolons to determine the end of a statement. If no semicolon is present, it will use a new line as the end of the statement. The only time it's necessary to use a semicolon is if you want to put two statements on the same line, one right after another.
All this being said, it's best practice to always end your statements with semicolons
To avoid confusion and to avoid bugs that could be painful to find.
分号在 javascript 中是可选的。但建议添加它。
Semi-colons are optional in javascript. But it is recommended to add it.
有时,如果您在 Linter 设置为检测分号的地方不使用分号,您的 Linter 设置将会触发。但是,某些分号在 JavaScript 中是可选的,包括换行符之前的分号。感谢自动分号插入 (ASI)。
ASI 只是一组关于何时分号是可选的规则,它实际上并不将分号插入到您的代码中。
一些分号是必要的。必要分号的示例包括 for 循环和 do-while 循环的开头。
另外要小心,因为尽管省略可选的分号是有效的代码,但某些工具(例如缩小器)被编写来解释这些分号,因此可能会使用这些工具之一引发错误。
Sometimes your Linter settings will trigger if you don't use semicolons in places where your Linter is set up to detect them. However, some semicolons are optional in JavaScript including the semicolons put just before a line-break. Thanks to automatic semi colon insertion (ASI).
ASI is just a set of rules for when semicolons are optional, it doesn't actually insert semicolons into your code.
Some semicolons ARE necessary. Sxamples of necessary semicolons include the head of the a for loop and do-while loops.
Also be careful because although omitting optional semi-colons is valid code some tools like minifiers are written to interpret those semicolons so it could throw an error with one of those tools.