JavaScript 格式:大括号必须与 if/function/etc 关键字在

JavaScript formatting: must braces be on the same line as the if/function/etc keyword?(JavaScript 格式:大括号必须与 if/function/etc 关键字在同一行吗?)
本文介绍了JavaScript 格式:大括号必须与 if/function/etc 关键字在同一行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么在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 关键字在同一行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)