JavaScript 格式:大括号必须与 if/function/etc 关键字在同一行吗?

发布于 2024-09-28 03:29:42 字数 575 浏览 3 评论 0原文

可能的重复:
为什么结果会因 JavaScript 中大括号的放置位置而异代码

我们的公司政策规定,在 PHP 中,左大括号应单独成行以提高可读性,以便它们可以与右大括号对齐;因此:

if (true)
{
    ...
}

但在 JS 中,它们应该保持在同一行,以防浏览器错误解释它时出现问题

if (true) {
    ...

上面的斜体部分是合理的担忧吗?

PS - 我怀疑这个问题已经在这里被问过,但我还没有找到与我完全匹配的问题。抱歉,如果它在那里但我没有找到它。

Possible Duplicate:
why results varies upon placement of curly braces in javascript code

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)
{
    ...
}

but in JS they should be kept on the same line, in case there are problems with browsers incorrectly interpretting it.

if (true) {
    ...

Is the above italic part a legitimate concern?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨敛清荷 2024-10-05 03:29:42

是的,这在某些极端情况下很重要。

问题不在于“浏览器错误地解释它”。根据 ECMAScript 规范,这种狡猾的行为是正确的。不表现出这种行为的 JavaScript 实现将不符合规范。

一个例子。这个函数被破坏了:

function returnAnObject {
    return
    {
        foo: 'test'
    };
}

它应该返回一个对象,但实际上什么也没返回。 JavaScript 是这样解释的:

function returnAnObject {
    return;
    {
        foo: 'test'
    };
}

Yes, it matters in certain corner cases.

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'
    };
}

It's supposed to return an object, but actually returns nothing. JavaScript interprets it like so:

function returnAnObject {
    return;
    {
        foo: 'test'
    };
}
痴情换悲伤 2024-10-05 03:29:42

JS 中的解释,通常是当你的行没有分号时,它默认添加在行尾。为了避免这种情况并增加可读性,大括号通常与 IF、WHILE、Function 等添加在同一行。

据我所知,JS 中的此功能称为隐式分号插入。

The interpretation in JS, is usually when you have line without semi-colon, it is by default added at the end of line. To avoid such things and to increase readability, the braces are usually added on same line as IF, WHILE, Function etc.

This feature in JS is referred to as implicit semicolon insertion as far as I know.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文