简体   繁体   中英

Javascript - create array between two date objects

Question

I am attempting to build an array between two JS objects. It appears that my objects are being created correctly, and in fact that the code below is running.

The unexpected behavior is that every object in my output array is transforming to match the last date that I looped through. ie if I loop, whatever my todate_dateobj is, I get an entire array of just that value.

I have to do some debugging wrt the actual start/end dates being correct, but I can handle that -- what I'm stymied by is the behavior described above.

I am very new to javascript. I imagine this is some issue with mutation? Any guidance would be appreciated.

I left the console logs in just because why take them out?

Code

function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {
    // return an array of dateojects from fromdate to todate
    var current_date = fromdate_dateobj;
    var return_array = []

    while (current_date <= todate_dateobj) {
        return_array[return_array.length] = current_date; // I have read that this is generally faster that arr.push()
        var tomorrow = new Date(current_date.getTime() + 86400000);
        console.log('tomorrow: ', tomorrow);
        current_date.setTime(tomorrow);
        console.log('current_date: ', current_date)
        console.log("build_dateobjs_array : ", return_array);
    };

    return return_array;
};

Date objects are mutable. This line:

current_date.setTime(tomorrow);

...changes the state of the Date object that current_date refers to, which you never change.

So you're storing the same object repeatedly in return_array . Instead, make a copy of the Date :

return_array[return_array.length] = new Date(+current_date);

Also, it's probably best to change

    var current_date = fromdate_dateobj;

to

    var current_date = new Date(+fromdate_dateobj);

so you're not modifying the Date that was passed in.


Side note: There's no need for the round-trip to milliseconds, simply:

function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {
    // return an array of dateojects from fromdate to todate
    var current_date = new Date(+fromdate_dateobj);
    var return_array = [];

    while (current_date <= todate_dateobj) {
        return_array[return_array.length] = new Date(+current_date);
        current_date.setDate(current_date.getDate() + 1);
    };

    return return_array;
}

(There's also no reason to put a ; at the end of a function declaration.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM