我正在尝试基于一个已经存在的名为weekArray的数组(包含一组工作日)的模型来创建一个名为availabilityArray的多个星期的数组。新数组应该以weekArray中的原始项开始,然后在每个for循环周期之后将新修改的项按组推入。现在的问题是,availabilityArray中的所有项目集看起来都与以前的集相似,而更改为推入的最后修改的集。
请有人能告诉我我错了吗?这是我的代码:
const weekArray = [
this.monday,
this.tuesday,
this.wednesday,
this.thursday,
this.friday,
this.saturday,
this.sunday
];
console.log(weekArray);
const availabilityArray = [];
const newArray = [];
for (let i = 0; i < 3; i++) {
weekArray.forEach(item => {
//Add 1 week to each week number
item.weekNumber = item.weekNumber + i;
//Add 7 days to each date
item.date = new Date(Date.parse(item.date) + i * 7 * 8.64e7);
newArray.push(item);
});
availabilityArray.push(...newArray);
}
console.log(availabilityArray) //It prints out a repetition of the last set of pushed in objects.
答案 0 :(得分:0)
正如@IceMetalPunk在评论中指出的那样,您需要使用要推送的数据创建一个新对象。我试图根据您提供的代码来重现weekArray
包含的数据,但是这些值可能与您所拥有的不完全相同。
const weekArray = [
{"weekNumber":25,"date":1561359600000},
{"weekNumber":25,"date":1561446000000},
{"weekNumber":25,"date":1561532400000},
{"weekNumber":25,"date":1561618800000},
{"weekNumber":25,"date":1561705200000},
{"weekNumber":25,"date":1561791600000},
{"weekNumber":25,"date":1561878000000}
];
console.log(weekArray);
const availabilityArray = [];
const newArray = [];
for (let i = 0; i < 3; i++) {
weekArray.forEach(item => {
//Create a new item with an incremented weekNumber value
//and a date 7 days after the given date value
let newItem = {
"weekNumber": item.weekNumber + i,
"date": item.date + (i*7*8.64e7)
};
newArray.push(newItem);
});
availabilityArray.push(...newArray);
}
console.log(availabilityArray)