【问题标题】:Why map method does not return array of object?为什么map方法不返回对象数组?
【发布时间】:2020-02-03 09:53:48
【问题描述】:
let x = {a:1,b:2,c:3}
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return ({i :x[i]});
})

为什么是结果

[{i: 1},{i: 2},{i: 3}]

?在控制台中,正在打印 i 的值,即 a、b、c。退货期间会发生什么?

【问题讨论】:

  • 代码中的x 是什么?
  • 上面的代码确实返回一个对象数组。是什么让你认为它没有?另外,x 是什么?
  • 如果你想使用变量的value作为对象的属性,你应该使用方括号[i]
  • 您的问题已得到解答

标签: javascript array.prototype.map


【解决方案1】:

为什么map方法不返回对象数组?

确实如此。

退货期间会发生什么?

return ({i :x[i]}); 行表示:

  • 创建一个对象。
  • 给它一个名为"i" 的属性(不是i,实际的文字名称"i"),其值来自x[i]
  • 将其作为此映射迭代的值返回,该值将在结果数组中使用。

结果是一组对象,每个对象都有一个名为 "i" 的属性。

如果您打算使用i,则需要使用计算属性名称。对象文字周围的() 也没有理由:

return {[i]: x[i]};
//      ^^^------------- computed property name

现场示例:

let x = {a:1,b:2,c:3};
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return {[i]: x[i]};
});
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}

这是在 ES2015 中引入的。在 ES5 及更早版本中,您必须先创建对象,然后再向其添加属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2020-06-24
    相关资源
    最近更新 更多