gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:58:54 24 4
gpt4 key购买 nike

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。返回期间会发生什么?

最佳答案

Why map method does not return array of object?

确实如此。

What happens during return?

return ({i :x[i]}); 行的含义是:

  • 创建一个对象。
  • 为其指定一个名为 "i" 的属性(不是 i,而是实际的文字名称 "i") 与 x[i] 中的值。
  • 返回该值作为本次 map 迭代的值,该值将在结果数组中使用。

结果是一组对象,每个对象都有一个名为“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 及更早版本中,您必须先创建对象,然后再向其添加属性。

关于javascript - 为什么map方法不返回对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58246906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com