返回对象的 ECMAScript 6 箭头函数 [英] ECMAScript 6 arrow function that returns an object

查看:26
本文介绍了返回对象的 ECMAScript 6 箭头函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当从箭头函数返回一个对象时,似乎有必要使用一组额外的 {} 和一个 return 关键字,因为在语法.

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"}; }.

如果箭头函数返回对象以外的任何内容,则 {}return 是不必要的,例如: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"} 抛出 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屋!

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