[英]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:线的意思:
"i"
(not the value of i
, the actual literal name "i"
) with the value from x[i]
."i"
的属性(不是i
的值,实际的文字名称"i"
),其值来自x[i]
。 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.