ECMAScript 6返回对象的箭头函数 [英] ECMAScript 6 arrow function that returns an object
问题描述
从箭头函数返回一个对象时,似乎需要使用一组额外的 {}
和一个返回
关键字,因为语法含糊不清。
When returning an object from an arrow function, it seems that it is necessary to use an extra set of {}
and a return
keyword because of an ambiguity in the grammar.
这意味着我无法写 p => {foo:bar}
,但必须写 p => {return {foo:bar}; }
。
That means I can’t write p => {foo: "bar"}
, but have to write p => { return {foo: "bar"}; }
.
如果箭头函数返回除对象以外的任何内容,则 {}
和返回
是不必要的,例如: p => foo
。
If the arrow function returns anything other than an object, the {}
and return
are unnecessary, e.g.: p => "foo"
.
p => {foo:bar}
返回 undefined
。
修改后的 p => {foo:bar}
throws SyntaxError
:意外令牌:':
'。
A modified p => {"foo": "bar"}
throws "SyntaxError
: unexpected token: ':
'".
有什么东西显而易见我错过了吗?
Is there something obvious I am missing?
推荐答案
您必须将返回的对象文字包装成括号。否则花括号将被视为表示函数的主体。以下作品:
You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:
p => ({ foo: 'bar' });
您不需要将任何其他表达式括在括号中:
You don't need to wrap any other expression into parentheses:
p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;
依此类推。
参考: MDN - 返回对象文字
这篇关于ECMAScript 6返回对象的箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!