gpt4 book ai didi

JavaScript:在给定 .map() 输入参数的情况下创建对象而不使用 ES6 {} 快捷方式

转载 作者:行者123 更新时间:2023-11-29 20:35:11 24 4
gpt4 key购买 nike

我目前正在使用 JavaScript ES6 从 .map 数组方法创建以下输出对象。

const indexAndValue = (arr) => {

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

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

输出代码为:

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

如何在不使用 {} 快捷方式的情况下获得相同的输出?我尝试了以下代码:

const indexAndValue = (arr) => {

let obj = {};

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

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

此代码返回错误:

[ 22, 33, 44, 55 ]

最佳答案

您需要将对象的声明移到回调中。如果在外部,您将重用该对象,并且所有元素都包含相同的对象,由于具有相同的对象引用,因此具有最新的更新。

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]));

关于JavaScript:在给定 .map() 输入参数的情况下创建对象而不使用 ES6 {} 快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56907638/

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