問題描述
可能重復:
為什么在javascript中放置花括號時結果會有所不同代碼
我們的公司政策規定,在 PHP 中,左大括號應該在自己的行中以提高可讀性,以便它們可以與右大括號對齊;因此:
We have company policies that dictate that in PHP opening curly braces should be on their own lines for readability and so that they can line-up with the closing brace; thus:
if (true)
{
...
}
但在 JS 中它們應該保持在同一行,以防瀏覽器錯誤解釋它出現問題.
but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.
if (true) {
...
上述斜體部分是否合理?
PS - 我懷疑這里已經有人問過這個問題,但我沒有找到與我的完全匹配的問題.抱歉,如果它在那里,但我沒有找到它.
PS - I suspect that this question has been asked on here already, but I've not found a question that exactly matches mine. Apologies if it's there and I didn't find it.
推薦答案
是的,這在某些極端情況下很重要.
Yes, it matters in certain corner cases.
問題不在于瀏覽器錯誤地解釋它".根據 ECMAScript 規范,狡猾的行為是正確的.沒有表現出這種行為的 JavaScript 實現將不符合規范.
And the problem isn't with "browsers incorrectly interpreting it". The dodgy behaviour is correct according to the ECMAScript specifications. A JavaScript implementation that didn't exhibit this behaviour would not be spec-compliant.
一個例子.這個函數壞了:
An example. This function is broken:
function returnAnObject {
return
{
foo: 'test'
};
}
它應該返回一個對象,但實際上什么也沒返回.JavaScript 是這樣解釋的:
It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:
function returnAnObject {
return;
{
foo: 'test'
};
}
這篇關于JavaScript 格式:大括號必須與 if/function/etc 關鍵字在同一行嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!