简体   繁体   English

为什么 map 方法不返回 object 的数组?

[英]Why map method does not return array of object?

let x = {a:1,b:2,c:3}
let result = Object.keys(x).map((i) => {
  console.log(i) ;
  return ({i :x[i]});
})

why result is为什么结果是

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

? ? In console, value of i ie a,b,c is being printed.在控制台中,正在打印 i 的值,即 a,b,c。 What happens during return?退货期间会发生什么?

Why map method does not return array of object?为什么 map 方法不返回 object 的数组?

It does.确实如此。

What happens during return?退货期间会发生什么?

The return ({i:x[i]}); return ({i:x[i]}); line means:线的意思:

  • Create an object.创建 object。
  • Give it a property called "i" (not the value of i , the actual literal name "i" ) with the value from x[i] .给它一个名为"i"的属性(不是i,实际的文字名称"i" ),其值来自x[i]
  • Return that as the value for this map iteration, which will be used in the result array.将其作为此 map 迭代的值返回,它将在结果数组中使用。

The result is an array of objects, each with one property called "i" .结果是一组对象,每个对象都有一个名为"i"的属性。

If you meant to use the value of i , you'd need to use a computed property name.如果您打算使用i,则需要使用计算的属性名称。 There's also no reason for the () around the object literal: object 文字周围的()也没有理由:

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

Live Example:现场示例:

 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; }

This was introduced in ES2015.这是在 ES2015 中引入的。 In ES5 and earlier, you'd have to create the object first, then add the property to it afterward.在 ES5 及更早版本中,您必须先创建 object,然后再将属性添加到其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM