简体   繁体   English

我可以在所有JavaScript版本中(如果有的话)在行尾省略每个分号吗?

[英]May I omit every semicolon at the end of line in all version (if any) of JavaScript?

I'm learning JavaScript and I somehow figured out that I may skip typing ; 我正在学习JavaScript,但我莫名其妙地发现我可以跳过输入; at the end of a line, as long as there's only one statement in that line. 在一行的末尾,只要该行中只有一个语句即可。 In fact I'm used to this a bit; 实际上,我已经习惯了这一点。 I developed a simple iOS app with Swift which supports this kind of syntax too. 我用Swift开发了一个简单的iOS应用程序,它也支持这种语法。

But what I'm wondering is whether there's a specific version or something of JavaScript which does not allow programmers to omit the last semicolon. 但是我想知道的是,是否有特定版本的JavaScript或某种不允许程序员省略最后一个分号的JavaScript。 Lots of languages have had changes in syntax; 许多语言的语法都有变化。 so I guess JavaScript might have this kind of problem. 所以我想JavaScript可能有这种问题。

Note that while all versions of JavaScript support ASI, there are pitfalls of ASI that will mean you can't get rid of all semicolons. 请注意,尽管所有版本的JavaScript都支持ASI,但仍有ASI的陷阱,这意味着您无法摆脱所有分号。

For example, the following will not work as you might expect: 例如,以下内容将无法正常运行:

function foo() { return [2, 3] }

var x, y, i, j
j = 2
i = j
[x,y] = foo()

You might expect that i , j , and x will equal 2, and y will equal 3, which is what would happen if every line were semicolon-terminated. 您可能希望ijx等于2,而y等于3,如果每行以分号结尾,则会发生这种情况。 However, that is not the case. 但是,事实并非如此。

In fact, i is [2,3] , while x and y are undefined . 实际上, i[2,3] ,而xyundefined When ASI ran on that section of code, it interpreted the final two lines as a property access: 当ASI在该代码段上运行时,它将最后两行解释为属性访问:

i = j[x,y] = foo()

while it was probably intended to be a destructuring operation: 虽然它原本打算成为破坏性的行动:

i = j;
[x,y] = foo();

A method to get around this is to use "defensive semicolons" before any line beginning with [] or () that is not intended to be treated as the continuation of the previous statement. 解决此问题的方法是在不以[]或()开头的任何行之前使用“防御分号”,而该行不应被视为上一条语句的继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM