3
A
回答
5
这是因为ASI(自动分号插入)允许您避免使用分号。
例如,你可以写这样的代码,并没有错误:
var a = 1
a.fn = function() {
console.log(a)
}
看到了吗?没有一个分号。
但是,有些情况下分号未插入。基本上,在真实项目中,有一种情况不是:下一行以括号开头。
JavaScript解析器将把下一行作为参数,而不是自动添加分号。
例子:
var a = 1
(function() {})()
// The javascript parser will interpret this as "var a = 1(function() {})()", leading to a syntax error
为了避免这种情况,有几种方法:
- 在一行的开头添加一个分号用括号开始(这是在告诉你的代码完成)
使用以下结构:
!function() {}()
1
JavaScript有自动分号插入(见ECMAScript Language Specification节7.9):
There are three basic rules of semicolon insertion:
- When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
- The offending token is separated from the previous token by at least one LineTerminator.
- The offending token is
}
.- When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
通常你可以省略JavaScript文件中的最后一个分号(第二条规则)。如果您的应用程序通过合并多个文件来创建JavaScript代码,则会导致语法错误。由于;
本身就是空的语句,因此可以使用它来防止此类语法错误。
0
很好的解释可以在这里找到:
http://mislav.uniqpath.com/2010/05/semicolons/
(见第 “唯一真正的陷阱没有分号编码时”)
var x = y
(a == b).print()
被评估为
var x = y(a == b).print()
底线,这是一个很好的做法,在每一行之前加上一个分号,以(characther 。
相关问题
- 1. 函数之前的&符号(&)是什么意思?
- 2. 函数名称前的星号是什么意思?
- 3. 函数参数之后和函数体之前的char * in_str是什么意思?
- 4. - .indexOf()之前的意思是什么?
- 5. 函数($)是什么意思?
- 6. 什么意思前缀::意思是
- 7. C#中变量名之前的@符号是什么意思?
- 8. 类声明之前的方括号是什么意思?
- 9. 新操作符之前的括号 - 是什么意思?
- 10. &符号是什么意思?
- 11. 冒号是什么意思?
- 12. 问号是什么意思?
- 13. 符号“⊇”是什么意思?
- 14. scanf()函数中的%符号之后的符号是什么意思?
- 15. 数字的分数是什么意思
- 16. 是什么意思:是什么意思?
- 17. 语句中的问号和冒号是什么意思?这是什么意思?
- 18. subs或函数参数中的问号是什么意思?
- 19. C++中数据类型之后的符号'^'是什么意思?
- 20. “$”在Delphi中的数字之前是什么意思?
- 21. 符号“#!”是什么意思?在Python中的意思是?
- 22. :: at函数名是什么意思?
- 23. javascript:函数语法是什么意思?
- 24. get_the_terms()wordpress函数是什么意思?
- 25. 这个宏函数是什么意思?
- 26. 这个C++函数是什么意思?
- 27. 函数(el,ev)是什么意思?
- 28. BASIC:函数名称末尾的感叹号是什么意思?
- 29. 围绕函数名称的括号是什么意思?
- 30. 函数中的空括号是什么意思?
这是一个分号。如果在另一个缺少尾随分号的文件之后导入文件,可能会出现这种情况。 – Pointy 2012-04-06 14:12:16
@积分谢谢。你可以将它发布在答案中,以便我可以接受它来结束这个问题。 – wong2 2012-04-06 14:15:55