【发布时间】:2023-01-26 16:26:42
【问题描述】:
我需要创建一个结果数组,以创建一个简单的示例来减少我的功能。
let startDate = new Date("2022-04-05"); // starting date
let endDate = new Date("2022-04-06"); // ending date
let result = await cycleThroughDays(startDate, endDate);
console.log("result", result)
async function cycleThroughDays(startDate, endDate) {
let res = [];
for (let currentDate = startDate; currentDate <= endDate; currentDate.setDate(currentDate.getDate() + 1)) {
console.log(currentDate)
res.push(currentDate);
}
console.log(res)
return res;
}
输出是:
2022-04-05T00:00:00.000Z
2022-04-06T00:00:00.000Z
[ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
result [ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
我希望像这样的数组
result [ 2022-04-05T00:00:00.000Z, 2022-04-06T00:00:00.000Z ]
但我明白了
result [ 2022-04-07T00:00:00.000Z, 2022-04-07T00:00:00.000Z ]
【问题讨论】:
-
您正在向数组中推送一个您将在事后更改的对象。所以在数组中,你在多个槽中有相同的实例。您应该改为克隆要推送到数组中的对象,以便每个插槽都是不同的日期实例,就像这样
res.push(new Date(currentDate));
标签: javascript node.js