gpt4 book ai didi

javascript - 循环遍历每次迭代并将其保存到数组中

转载 作者:行者123 更新时间:2023-12-01 03:56:35 26 4
gpt4 key购买 nike

考虑到这个主题,我检查了这里的很多主题,但解决方案似乎不适合我。我想我有一些逻辑问题。我的代码很简单。我有两个数组(第一个包含三个字符串,第二个包含三个日期)

我想要做的就是将第一个数组中的第一个字符串与第二个数组中的第一个日期存储在一个对象中。

我在函数 theMainFunc() 中创建的数组的代码的问题是使用每个数组的最后一个索引保存 3 个对象,而不是像我需要的那样匹配它们。

这是代码:

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'];
var dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)];

function objectCreator (dlcObject,dlcName,dlcDate) {
dlcObject.name = dlcName;
dlcObject.date = dlcDate;
return dlcObject;
}

function theMainFunc() {

var dlcDetails = {};
var i = 0;
var storage = [];
var x;

for (i; i <= 2; i++){
x = objectCreator(dlcDetails,dlcNameList[i],dlcReleaseDate[i]);
storage[i] = x;
}

return storage; //This returns an array with three "Same" objects. Not what I want to really acheive
}

console.log(theMainFunc())

最佳答案

给你(:

注意:您不必在每次迭代时创建新对象,您可以使用 Array#forEach 并将已设置属性和键的对象推送到结果数组。

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'],
dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)],
result = [];

dlcNameList.forEach((v,i) => result.push({name : v, date : dlcReleaseDate[i]}));
console.log(result);

关于javascript - 循环遍历每次迭代并将其保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42611093/

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