箭头函数返回的对象中出现“意外令牌”语法错误
问题描述:
以下是有问题的代码:
const data =
results.responses.map((response, idx) =>
{ id: idx+1,
name: response.name,
email: response.email,
comment: response.comment
}
)
我正在使用babel将es6代码翻译成javascript。这是错误消息:
I am using babel to translate the es6 code to javascript. This is the error message:
Module build failed: SyntaxError: /Users/antkong/dev/project/form.js: Unexpected token (60:14)
58 | results.responses.map((response, idx) =>
59 | { id: idx+1,
> 60 | name: response.name,
| ^
61 | email: response.email,
62 | comment: response.comment
63 | }
为什么会出现语法错误?
Why there is a syntax error there?
答
在您的示例中,JavaScript处理 {
和}
作为块语句而不是对象文字。用括号括起你的对象((
和)
)它会起作用。
In your example JavaScript treats {
and }
as a block statement instead of object literal. Wrap your object in brackets ((
and )
) and it will work.
更正后的代码:
const data =
results.responses.map((response, idx) =>
({ id: idx+1,
name: response.name,
email: response.email,
comment: response.comment
})
)