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