返回对象的ECMAScript 6箭头函数

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.

That means I can’t write p => {foo: "bar"}, but have to write p => { return {foo: "bar"}; }.

If the arrow function returns anything other than an object, the {} and return are unnecessary, e.g.: p => "foo".

p => {foo: "bar"} returns undefined.

A modified p => {"foo": "bar"} throws SyntaxError: unexpected token: ':'”.

Is there something obvious I am missing?

Green樱2020/03/11 23:35:13

您可以随时查看更多定制解决方案:

x => ({}[x.name] = x);
梅老丝2020/03/11 23:35:13

问题:

当您这样做时:

p => {foo: "bar"}

JavaScript解释器认为您正在打开一个多语句代码块,在该块中,您必须明确提及return语句。

解:

如果箭头函数表达式具有单个语句,则可以使用以下语法:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

但是,如果要具有多个语句,则可以使用以下语法:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

在上面的示例中,第一组花括号打开了一个多语句代码块,第二组花括号用于动态对象。在箭头功能的多语句代码块中,您必须显式使用return语句

有关更多详细信息,请查看Mozilla Docs中的JS Arrow函数表达式

乐理查德2020/03/11 23:35:13

正确的方法

  1. 正常返回对象

const getUser = user => {return { name: user.name, age: user.age };};

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

  1. (js表达式)

const getUser = user => ({ name: user.name, age: user.age });

const user = { name: "xgqfrms", age: 21 };

console.log(getUser(user));
//  {name: "xgqfrms", age: 21}

说明

图片

在这里可以找到相同的答案!

https://github.com/lydiahallie/javascript-questions/issues/220

https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript

小胖Eva2020/03/11 23:35:13

您可能想知道,为什么语法有效(但不能按预期工作):

var func = p => { foo: "bar" }

这是因为JavaScript的标签语法

因此,如果将上面的代码转换为ES5,它应该看起来像:

var func = function (p) {
  foo:
  "bar"; //obviously no return here!
}