【问题标题】:unexpected token : using map to form array of object [duplicate]意外令牌:使用地图形成对象数组[重复]
【发布时间】:2017-11-06 03:21:04
【问题描述】:

我想制作这个

[
        {name: "james", age: 10},
        {name: "john", age: 12},
        {name: "johnny", age: 56}
    ]

我下面的代码失败了,得到了预期的令牌?

let x = [
    {name: "james", age: 10, school: "London"},
    {name: "john", age: 12, school: "India"},
    {name: "johnny", age: 56, school: "USA"}
]

let y = x.map(obj => {name:obj.name, age:obj.age})

console.log(y)

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    你错过了 () 这样的更改 ({name:obj.name, age:obj.age})

    您必须将返回的对象文字包装到括号中。否则 花括号将被视为表示函数的主体。下一个 作品:

    Reference question

    let x = [
        {name: "james", age: 10, school: "London"},
        {name: "john", age: 12, school: "India"},
        {name: "johnny", age: 56, school: "USA"}
    ]
    
    let y = x.map(obj => ({name:obj.name, age:obj.age}))
    
    console.log(y)

    【讨论】:

    • new Object({name:obj.name, age:obj.age}) 也可以吗?
    • @AyoubLaazazi .. 当然可以。但是({}) 就足够了。短格式声明。
    【解决方案2】:

    使用箭头表达式创建对象时,您需要将主体包裹在括号中,否则将被解析为箭头函数:

    let y = x.map(obj => ({name: obj.name, age: obj.age}));
    

    【讨论】:

      【解决方案3】:

      作为参考,这也可以,并且是一样的:

      let x = [
          {name: "james", age: 10, school: "London"},
          {name: "john", age: 12, school: "India"},
          {name: "johnny", age: 56, school: "USA"}
      ];
      
      let y = x.map(obj => {
        return { name:obj.name, age:obj.age };
      });
      
      console.log(y);

      【讨论】:

        猜你喜欢
        • 2018-03-14
        • 2017-07-11
        • 1970-01-01
        • 2023-03-06
        • 2016-04-15
        • 2019-01-11
        • 2016-05-30
        • 1970-01-01
        • 2017-11-05
        相关资源
        最近更新 更多