Javascript 返回对象的 ECMAScript 6 箭头函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28770415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ECMAScript 6 arrow function that returns an object
提问by jkschneider
When returning an object from an arrow function, it seems that it is necessary to use an extra set of {}and a returnkeyword because of an ambiguity in the grammar.
当从箭头函数返回一个对象时,由于语法上的歧义,似乎需要使用额外的一组{}和return关键字。
That means I can't write p => {foo: "bar"}, but have to write p => { return {foo: "bar"}; }.
这意味着我不能写p => {foo: "bar"},但必须写p => { return {foo: "bar"}; }。
If the arrow function returns anything other than an object, the {}and returnare unnecessary, e.g.: p => "foo".
如果箭头函数返回对象以外的任何内容,则{}和return是不必要的,例如:p => "foo"。
p => {foo: "bar"}returns undefined.
p => {foo: "bar"}返回undefined。
A modified p => {"foo": "bar"}throws “SyntaxError: unexpected token: ':'”.
修改后p => {"foo": "bar"}抛出“ SyntaxError:意外标记:' :'”。
Is there something obvious I am missing?
有什么明显的我遗漏了吗?
回答by alexpods
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$/;
and so on.
等等。
Reference: MDN - Returning object literals
回答by Petr Odut
You may wonder, why the syntax is valid (but not working as expected):
您可能想知道,为什么语法是有效的(但没有按预期工作):
var func = p => { foo: "bar" }
It's because of JavaScript's label syntax:
这是因为JavaScript 的标签语法:
So if you transpile the above code to ES5, it should look like:
因此,如果您将上述代码转译为 ES5,它应该如下所示:
var func = function (p) {
foo:
"bar"; //obviously no return here!
}
回答by Paul McBride
If the body of the arrow function is wrapped in curly braces, it is not implicitly returned. Wrap the object in parentheses. It would look something like this.
如果箭头函数的主体用花括号括起来,则不会隐式返回。将对象括在括号中。它看起来像这样。
p => ({ foo: 'bar' })
By wrapping the body in parens, the function will return { foo: 'bar }.
通过将主体包裹在括号中,该函数将返回{ foo: 'bar }.
Hopefully, that solves your problem. If not, I recently wrote an article about Arrow functions which covers it in more detail. I hope you find it useful. Javascript Arrow Functions
希望这能解决您的问题。如果没有,我最近写了一篇关于 Arrow 函数的文章,其中更详细地介绍了它。希望对你有帮助。Javascript 箭头函数
回答by xgqfrms
the right ways
正确的方法
- normal return object
- 正常返回对象
const getUser = user => {return { name: user.name, age: user.age };};
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
- (js expressions )
- (js 表达式)
const getUser = user => ({ name: user.name, age: user.age });
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
explain
解释


The same answer can be found here!
可以在这里找到相同的答案!
https://github.com/lydiahallie/javascript-questions/issues/220
https://github.com/lydiahallie/javascript-questions/issues/220
https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript
https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript
回答by Rusty
Issue:
问题:
When you do are doing:
当你在做:
p => {foo: "bar"}
JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.
JavaScript 解释器认为您正在打开一个多语句代码块,并且在该块中,您必须明确提及 return 语句。
Solution:
解决方案:
If your arrow function expressionhas a single statement, then you can use the following syntax:
如果您的箭头函数表达式只有一个statement,那么您可以使用以下语法:
p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})
But if you want to have multiple statementsthen you can use the following syntax:
但是如果你想有多个语句,那么你可以使用以下语法:
p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}
In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements
在上面的例子中,第一组大括号打开一个多语句代码块,第二组大括号用于动态对象。在箭头函数的多语句代码块中,必须显式使用 return 语句
For more details, check Mozilla Docs for JS Arrow Function Expressions
有关更多详细信息,请查看Mozilla Docs for JS Arrow Function Expressions
回答by SirtusKottus
You can always check this out for more custom solutions:
您可以随时查看更多自定义解决方案:
x => ({}[x.name] = x);

