如何在 Javascript 中循环使用几个月
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27935267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through months in Javascript
提问by BoVut
I'm trying to generate a list of string dates in months (i.e. ["Oct 2014", "Nov 2014",... "Jan 2015" ]) using the code here:
我正在尝试使用此处的代码生成以月为单位的字符串日期列表(即 ["Oct 2014", "Nov 2014",... "Jan 2015" ]):
var resultList = [];
var date = new Date("October 13, 2014");
var endDate = new Date("January 13, 2015");
var monthNameList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
while (date <= endDate)
{
var stringDate = monthNameList[date.getMonth()] + " " + date.getFullYear();
resultList.push(stringDate);
date.setDate(date.getMonth() + 1);
}
return resultList;
But when I run the code, the screen was frozen (like it was endless loop or something). I never have this problem when I generate daily date (i.e. date.getDate() +1 ). Am I missing something here?
但是当我运行代码时,屏幕被冻结(就像它是无限循环或其他东西)。当我生成每日日期(即 date.getDate() +1 )时,我从来没有遇到过这个问题。我在这里错过了什么吗?
采纳答案by Anthony Forloney
The problem is within your date.setDate(date.getMonth() + 1)
code as the MDN documentation states the setDate
function sets the dayto the specified Date
object. Therefore, it's not behaving as you had intended.
问题出在您的date.setDate(date.getMonth() + 1)
代码中,因为 MDN 文档指出该setDate
函数将日期设置为指定的Date
对象。因此,它的行为不符合您的预期。
To better illustrate the problem, the date
variable is initialized as Mon Oct 13 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
. When you call date.getMonth()
it returns 9
indicating the 10th month in the calendar year; so incrementing the value by 1 results in setting the dayof the date
variable to 10.
为了更好地说明问题,date
变量被初始化为Mon Oct 13 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
。当您调用date.getMonth()
它时,它会返回9
指示日历年的第 10 个月;因此将值增加 1 会导致将变量的日期设置date
为10。
On the next iteration, the monthhasn't changed, so the code re-executes date.getMonth()
which returns 9
again, so on and so on.
This unexpected behavior continues to repeat endlessly as the while
condition is never satisfied.
在下一次迭代中,月份没有改变,所以代码重新执行date.getMonth()
,9
然后再次返回,依此类推。由于while
条件永远不会满足,这种意外行为会继续无休止地重复。
The code should be updated to use setMonth
instead.
应更新代码以改为使用setMonth
。
回答by frosdqy
Use setMonth()
instead of setDate()
to sets the month of the date variable.
使用setMonth()
代替setDate()
来设置日期变量的月份。
date.setMonth(date.getMonth() + 1);