箭头函数返回的对象中出现“意外令牌”语法错误 [英] 'Unexpected token' syntax error in object returned by arrow function

查看:95
本文介绍了箭头函数返回的对象中出现“意外令牌”语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是有问题的代码:

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
    })
  )

这篇关于箭头函数返回的对象中出现“意外令牌”语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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