Home  >  Q&A  >  body text

javascript - Doesn't the simplest form of arrow function return an object? map(i => { name: i})

If the arrow function does not use curly braces{}, it is equivalent to returning directly

const arr = [1, 2, 3, 4]
arr.map(i => i) // 1 ,2 ,3, 4

But if I want to return an object, I cannot use the simplest form?

arr.map(i => { a: i}) // [undefined, undefined, undefined, undefined]

Must be enclosed in curly braces

arr.map(i => return {{ a: i}}) //  [Object, Object, Object, Object]
黄舟黄舟2705 days ago1100

reply all(2)I'll reply

  • phpcn_u1582

    phpcn_u15822017-06-14 10:55:09

    Definitely cannot use {} directly, because the function body is also implemented using {}, which will be considered to have an a:1expression

    in the function body.

    The simplest way to write it is to wrap it with ()

    arr.map(i => ({a: i}))

    reply
    0
  • 阿神

    阿神2017-06-14 10:55:09

    arr.map(i => ({ a: i})) 

    reply
    0
  • Cancelreply