当return语句和对象之间存在换行符时,Javascript函数无法返回对象? [英] Javascript function fails to return object when there is a line-break between the return statement and the object?
问题描述
以下是 jsfiddle
完整代码:
function foo1(){
return {msg: "hello1"};
}
function foo2(){
return
{msg: "hello2"};
}
// output = "foo1 = {"msg":"hello1"}"
console.log('foo1 = ' , JSON.stringify(foo1()));
//output = " foo2 = undefined "
console.log('foo2 = ' , JSON.stringify(foo2()));
两者之间的区别在于foo2, {msg:'你好'}
在它自己的新行中。我期待解析器忽略空格?
The difference between the two is that in foo2, the {msg: 'hello'}
is in its own new line. I was expecting the parser to ignore whitespaces?
推荐答案
tl; dr 换行符导致第二个函数中的'undefined'。 JavaScript在很多情况下不需要分号,只是在某些情况下假设它们(自动分号插入)。
tl;dr The line break is causing the 'undefined' in the second function. JavaScript doesn't require semicolons in a lot of cases and just assumes them in certain contexts (Automatic Semicolon Insertion).
在某些情况下,为了避免这种ASI问题和审美原因,我使用所谓的分组运营商。例如,使用 hoquet 模板化DSL(它将数组编译为s表达式转换为HTML),我喜欢对数组进行分组,以便它们清楚地显示HTML结构:
In certain cases, to avoid this ASI problem and for aesthetic reasons, I use the so-called grouping operator. For example, with the hoquet templating DSL (it compiles Arrays as s-expressions into HTML), I like to group the Arrays so that they clearly show the HTML structure:
return (
["ul"
, ["li"
, ["span", {class: "name"}, this.name]
, ["span", {id: "x"}, "x"]
]
]
);
这似乎比我更清楚,或者比我更加一致
which seems somewhat clearer, or more consistent to me than
return [
"ul",
[
"li",
["span", {class: "name"}, this.name],
["span", {id: "x"}, "x"]
]
];
并且它们的行数相同。但这确实是一个美学问题。
and they end up with the same number of lines. But it's a matter of aesthetics, really.
分组运算符只是评估其中的任何表达式。您通常会在立即调用函数表达式中看到这一点,您需要在通常是函数声明到表达式中,然后可以立即调用它(因此,名称)。但是,分组运算符的一个可能鲜为人知的特性是它也可以采用逗号分隔的表达式列表,例如
The grouping operator just evaluates whatever expression is inside of it. You see this commonly with Immediately Invoked Function Expressions, where you need to turn what would normally be a function declaration into an expression, which can then be immediately invoked (hence, the name). However, a perhaps lesser known feature of the grouping operator is that it can also take a comma-delimited list of expressions, e.g.
function() {
return (
doSideEffects(),
console.log("this is the second side effect"),
1 + 1
);
}
在这种情况下,它会评估每个表达式并仅返回最后一个表达式( 1 + 1)。
In this case it evaluates each of these expressions and returns only the last one (1 + 1).
这篇关于当return语句和对象之间存在换行符时,Javascript函数无法返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!