为什么结果会因花括号的位置而异? [英] Why do results vary based on curly brace placement?

查看:24
本文介绍了为什么结果会因花括号的位置而异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码片段取自 这篇文章,仅仅因为花括号的位置发生了一个变化就会产生不同的结果?

Why do the code snippets below, taken from this article, produce different results due to only a single change in the placement of curly braces?

当左花括号 { 在新行上时,test() 返回 undefined,并且不 - 它坏了:未定义" 显示在警报中.

When the opening curly brace { is on a new line, test() returns undefined, and "no - it broke: undefined" is displayed in the alert.

function test()
{
  return
  { /* <--- curly brace on new line */
    javascript: "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

当大括号与return在同一行时,test()返回一个对象,并提示fantastic".

When the brace is on the same line as return, test() returns an object, and "fantastic" is alerted.

function test()
{
  return { /* <---- curly brace on same line */
    javascript: "fantastic"
  };
}

var r = test();
try {
  alert(r.javascript); // does this work...?
} catch (e) {
  alert('no - it broke: ' + typeof r);
}

推荐答案

这是 JavaScript 的陷阱之一:自动分号插入.不以分号结尾但可能是语句结尾的行会自动终止,因此您的第一个示例看起来像这样:

That's one of the pitfalls of JavaScript: automatic semicolon insertion. Lines that do not end with a semicolon, but could be the end of a statement, are automatically terminated, so your first example looks effectively like this:

function test()
{
  return; // <- notice the inserted semicolon
  { 
    javascript: "fantastic"
  };
}

另请参阅 Douglas Crockford 的 JS 样式指南,其中提到了分号插入.

See also Douglas Crockford's JS style guide, which mentions semicolon insertion.

在您的第二个示例中,您返回一个对象(由花括号构建),其属性为 javascript,其值为 "fantastic",实际上与此相同:

In your second example you return an object (built by the curly braces) with the property javascript and its value of "fantastic", effectively the same as this:

function test() {
    var myObject = new Object();
    myObject.javascript = "fantastic";
    return myObject;
}

这篇关于为什么结果会因花括号的位置而异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆