javascript - 在箭头函数中使用 ComputedPropertyName 创建对象文字

标签 javascript ecmascript-6 arrow-functions computed-properties

如何转换:

const array = [10, 0, 90, 80, 50, 0, 60];
let id = 1;

const studentScores = array.map(function(score, index){
  return { [index]: score, student_id: id } 
});

console.log(studentScores)

进入粗箭头语法:

const studentScores = array.map((score, index) => { [index]: score, student_id: id } );

我的尝试抛出错误:

SyntaxError: Unexpected token :

最佳答案

您必须将对象字面量放在括号中,以使解析器相信它是一个对象字面量:

const studentScores = array.map((score, index) => ({ [index]: score, student_id: id }) );

通过将其括在括号中,解析器被迫将其解释为表达式,而不是语句 block { 字符具有歧义,当它是语句中的第一件事时,解析器总是假设“语句 block ”就是它所看到的。

关于javascript - 在箭头函数中使用 ComputedPropertyName 创建对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48264522/

相关文章:

firebase - 如何将 firebase-database 作为 es6 模块导入

javascript - 我可以在 document.getElementById() 中使用字符串变量吗?

javascript - RangeError 与 requestAnimationFrame

javascript - Javascript如何声明函数参数?

javascript - 从数组中删除多个对象并返回更新后的数组

Javascript 'this' 返回未定义的内部对象

javascript - 使用 Google map 绘制巴士路线

javascript - 警告 : Can't call setState (or forceUpdate) on an unmounted component

javascript - 在 Node js 控制台和浏览器之间的箭头函数中使用参数时的不同输出

javascript - 通过三元运算符映射数组赋值失败?