代码之家  ›  专栏  ›  技术社区  ›  Julius Dzidzevičius

在arrow函数[重复]中使用ComputedPropertyName创建对象文字

  •  0
  • Julius Dzidzevičius  · 技术社区  · 7 年前

    如何转换:

    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)

    转换为fat arrow语法:

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

    我的尝试引发错误:

    SyntaxError:意外标记:

    2 回复  |  直到 7 年前
        1
  •  4
  •   Pointy    7 年前

    您必须在对象文本中插入括号,以使解析器确信 对象文字:

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

    通过将其包装在括号中,解析器被迫将其解释为 表示 而不是 语句块 . 这个 { 字符具有这种模糊性,当它是语句中的第一件事时,解析器总是假定“语句块”就是它所看到的。

        2
  •  2
  •   Faly    7 年前

    含蓄地 使用箭头函数返回对象,并用括号将其包裹:

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