Javascript - create array between two date objects -


question

i attempting build array between 2 js objects. appears objects being created correctly, , in fact code below running.

the unexpected behavior every object in output array transforming match last date looped through. i.e. if loop, whatever todate_dateobjis, entire array of value.

i have debugging wrt actual start/end dates being correct, can handle -- i'm stymied behavior described above.

i new javascript. imagine issue mutation? guidance appreciated.

i left console logs in because why take them out?

code

function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {     // return array of dateojects fromdate todate     var current_date = fromdate_dateobj;     var return_array = []      while (current_date <= todate_dateobj) {         return_array[return_array.length] = current_date; // have read faster 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 mutable. line:

current_date.settime(tomorrow); 

...changes state of date object current_date refers to, never change.

so you're storing same object repeatedly in return_array. instead, make copy of date:

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

also, it's best change

    var current_date = fromdate_dateobj; 

to

    var current_date = new date(+fromdate_dateobj); 

so you're not modifying date passed in.


side note: there's no need round-trip milliseconds, simply:

function build_dateobjs_array(fromdate_dateobj, todate_dateobj) {     // return array of dateojects fromdate 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 no reason put ; @ end of function declaration.)


Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -