【问题标题】:create array of days in Javascript在 Javascript 中创建天数组
【发布时间】: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


【解决方案1】:

您需要创建一个单独的变量来保存当前日期,并在循环中递增该变量。尝试这个。

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 = [];
    let current = new Date(startDate);

    while (current <= endDate) {
        console.log(current);
        res.push(current);
        current.setDate(current.getDate() + 1);
    }
    console.log(res);
    return res;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 2011-03-17
    • 2018-07-09
    • 2019-07-18
    相关资源
    最近更新 更多