0

I am a bit confused about this one.

This piece of code works well but has strange behavior.

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate() + 1);

while (tmpcurdte < tmpenddte) {
  console.log("block date: " + tmpcurdte);
  blockdayarray[blockdayarray.length] = tmpcurdte;
  console.log("blockdayarray: " + blockdayarray);
  tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}

Output

block date :Sat Nov 12 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sat Nov 12** 2016 00:00:00 GMT+0100 (CET)
block date :Sat Dec 31 2016 00:00:00 GMT+0100 (CET)
blockdayarray :**Sun Nov 13** 2016 00:00:00 GMT+0100 (CET),**Sat Dec 31** 2016 00:00:00 GMT+0100 (CET)
block date :Sun Jan 01 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET),**Sun Jan 01 2017** 00:00:00 GMT+0100 (CET)
block date :Sat Feb 04 2017 00:00:00 GMT+0100 (CET)
blockdayarray :Sun Nov 13 2016 00:00:00 GMT+0100 (CET),Mon Jan 02 2017 00:00:00 GMT+0100 (CET),**Mon Jan 02 2017** 00:00:00 GMT+0100 (CET),Sat Feb 04 2017 00:00:00 GMT+0100 (CET)

As you can see the previous date in the array changes when I push a new one. Can anyone help/explain this?

2
  • why are you doing the eval thing? Commented Nov 10, 2016 at 8:47
  • read below. thx for taking the time to explorer my code :-) Commented Nov 10, 2016 at 9:19

1 Answer 1

1

It's because you're pushing the same Date object onto the array repeatedly, and changing its state.

Instead, you want to create a new Date object for the next day:

var tmpcurdte = eval(dataSource[i].startDate);
tmpcurdte.setDate(tmpcurdte.getDate()+1);

while (tmpcurdte < tmpenddte) {
    console.log("block date :" + tmpcurdte);
    blockdayarray[blockdayarray.length]=tmpcurdte;
    console.log("blockdayarray :" + blockdayarray);
    tmpcurdte = new Date(tmpcurdte.getTime());     // ***
    tmpcurdte.setDate(tmpcurdte.getDate() + 1);
}

Side note: I'm not quite sure what you're doing with that call to eval, but there's almost certainly a better way to do whatever it is you have that doing.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent,Your solution works fine. i also tough it was a reference thing but couldn’t figure it out . the eval is to parse a php returned date string as a date object. <br>I will change it afterwards but for now it works fine. i need this date object in a widget thx for your help, B

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.