问题描述
当从箭头函数返回一个对象时,似乎有必要使用一组额外的{}和一个返回语句,因为语法中有歧义:
When returning an object from an arrow function, it seems that it is necessary to use an extra set of {} and a return statement because of an ambiguity in the grammar:
p => {return {foo:'bar'}}
如果箭头函数返回任何其他内容,则{}和返回是不必要的,例如:
If the arrow function returns anything else, the {} and return are unnecessary, e.g.:
p => 'foo'
有没有什么明显的我缺少?
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$/;
等等。
这篇关于返回一个对象的ECMAScript6箭头函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!