JavaScript: Create Object given .map() input arguments without using ES6 {} Shortcut

问题: I am currently using JavaScript ES6 to create the following output object from a .map array method. const indexAndValue = (arr) => { return arr.map((elem, index) =...

问题:

I am currently using JavaScript ES6 to create the following output object from a .map array method.

const indexAndValue = (arr) => {

  return arr.map((elem, index) => {
    return { index, elem }
  }); 
}

indexAndValue([22, 33, 44, 55])

The output code is:

[ { index: 0, elem: 22 },
  { index: 1, elem: 33 },
  { index: 2, elem: 44 },
  { index: 3, elem: 55 } ]

How do I get the same output without using the {} shortcut? I tried the following code:

const indexAndValue = (arr) => {

  let obj = {}; 

  return arr.map((elem, index) => {
    return obj[index] = elem; 
  }); 
}

indexAndValue([22, 33, 44, 55])

This code returns incorrectly:

[ 22, 33, 44, 55 ]

回答1:

You need to move the declaration of object inside of the callback. If outside, you reuse the object and all elements contains the same object, with the latest update, because of the same object reference.

const indexAndValue = (arr) => {
  return arr.map((elem, index) => {
      var object = {};
      object.index = index;
      object.elem = elem;
    return object;
  }); 
}

console.log(indexAndValue([22, 33, 44, 55]));

  • 发表于 2019-07-08 00:27
  • 阅读 ( 284 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除