0

我正在尝试从给定的开始日期遍历日期。我陷入了围绕 nodeJS 和异步编程的永恒问题:

    getdates('2018-08-01', function(result) {
        console.log(result);
    })

    function getdates (startdate, callback) {
        let now = new Date();
        let start = new Date(startdate);
        let Dates = [];

        do {

            Dates.push(start);
            start.setDate(start.getDate() + 1);

        }
        while(now.getDate() != start.getDate())

        callback(Dates);         
    }

结果是:

[ 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z, 2018-08-07T00:00:00.000Z ]

只有今天日期的数组。

我知道是因为 NodeJS 的性质,但是我该如何解决这个问题或以正确的方式做到这一点?

最好的问候,克里斯蒂安

4

2 回答 2

1

它与异步编程无关,我不认为它是“永恒的”。

您正在创建 1 个日期对象并推送它。所以数组项是对同一个对象的引用。

这可能是一种粗略的方法:

getdates('2018-08-01', function(result) {
    console.log(result);
})

function getdates (startdate, callback) {
    const now = new Date();
    const start = new Date(startdate);
    let Dates = [];

    for(let i=0;i<(now.getDate() - start.getDate());i++ ){
        const d = new Date(startdate);
        d.setDate(d.getDate() + i);
        Dates.push(d);
    }

    callback(Dates);         
}
于 2018-08-07T12:08:10.563 回答
1

这与任何 Node.js 或异步范例无关。在 Java、C# 和大多数其他语言中也会发生同样的情况。

问题出在这一行:Dates.push(start);.

start是一个对象,因此它拥有引用。通过调用“push”,您可以将引用复制到数组中的下一个字段中。

您最终得到的数组中填充了对同一对象的引用,因此它们都具有相同的值 - 您为该对象设置的最后一个值。

这将正常工作

getdates('2018-08-01', function(result) {
    console.log(result);
})

function getdates (startdate, callback) {
    let now = new Date();
    let start = new Date(startdate);
    let Dates = [];

    do {

        Dates.push(new Date(start));
        start.setDate(start.getDate() + 1);

    }
    while(now.getDate() != start.getDate())

    callback(Dates);         
}

回调也不再使用(如果没有必要),它只会使您的代码可读性降低并且更难调试。

你可以只返回值 -

const dates = getdates('2018-08-01');
console.log(dates);

function getdates (startdate, callback) {
    let now = new Date();
    let start = new Date(startdate);
    let Dates = [];

    do {

        Dates.push(new Date(start));
        start.setDate(start.getDate() + 1);

    }
    while(now.getDate() != start.getDate())

    return Dates;
}

于 2018-08-07T12:08:20.537 回答