开发者

do...while stopping 2 months early?

开发者 https://www.devze.com 2023-01-30 01:44 出处:网络
var date = new Date(); do { var sel = date.toString(); document.write(sel + \"<br>\"); date.setDate(date.getDate()+1);
var date = new Date(); 
do {
    var sel = date.toString();
    document.write(sel + "<br>");
    date.setDate(date.getDate()+1);
   } while(date.getDate()开发者_运维知识库 != 2 && date.getMonth() != 2)

Why does this stop on Jan 1..?


Because at Jan 2, the first condition returns false and the execution stops. I assume you want the script to continue all the way to Feb 2, in which case your condition should look like this:

} while(date.getDate() != 2 || date.getMonth() != 1)
// Stops when day is 2 and month is 1 (February)

Or:

} while(!(date.getDate() == 2 && date.getMonth() != 1))

Both mean the same thing. Note that months are zero indexed so February is 1. This results in a output like this:

...
Fri Jan 28 2011 14:57:00 GMT+0200
Sat Jan 29 2011 14:57:00 GMT+0200
Sun Jan 30 2011 14:57:00 GMT+0200
Mon Jan 31 2011 14:57:00 GMT+0200
Tue Feb 01 2011 14:57:00 GMT+0200

http://jsfiddle.net/MF7bR/


Check http://jsfiddle.net/PYXeu/.

Jan 1rst have getDate == 2.

Edit: If you want this go to 2.02 check the code in http://jsfiddle.net/PYXeu/1/


Because in the second iteration .getDate is 2. The while can't execute. You need to increase it to 3 if you want it to stop once it has completed 2.

It also wouldn't hurt if you were more explicit in your code about what you're adding to the date.


When you hit March or 2. day of month, your loop won't be executed anymore. This is because months start from 0, so January is 0 and December is 11.


In javascript, the month starts at index 0 for January. You will need to adjust your loop accordingly for your needs.


I believe months start at 0, so on the 1st of January date.getMonth() == 0, which != 2.

0

精彩评论

暂无评论...
验证码 换一张
取 消