本文介绍了如何在Javascript中循环浏览数月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此处的代码生成几个月内
的字符串日期列表(即[ Oct 2014, Nov 2014,... Jan 2015])

I'm trying to generate a list of string dates in months (i.e. ["Oct 2014", "Nov 2014",... "Jan 2015" ]) using the code here:

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;

但是当我运行代码时,屏幕被冻结(就像是无休止的循环之类)。
生成每日日期(即date.getDate()+1)时,我从来没有这个问题。
我在这里缺少什么吗?

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.setDate( date.getMonth()+ 1)代码作为MDN文档指出函数将 day 设置为指定的 Date 对象。因此,它的行为并不符合您的预期。

The problem is within your date.setDate(date.getMonth() + 1) code as the MDN documentation states the setDate function sets the day to the specified Date object. Therefore, it's not behaving as you had intended.

为了更好地说明问题,将 date 变量初始化为 2014年10月13日星期一00:00:00 GMT-0400(东部夏令时间)。当您调用 date.getMonth()时,它返回 9 ,表示日历年中的第十个月。因此将值增加1会将 date 变量的 day 设置为 10

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 day of the date variable to 10.

在下一次迭代中, month 不变,因此代码重新执行 date.getMonth( ),它会再次返回 9 ,依此类推。
这种意外行为会不断重复,因为条件从未得到满足。

On the next iteration, the month hasn'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.

代码应更新为使用。

The code should be updated to use setMonth instead.

这篇关于如何在Javascript中循环浏览数月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 08:01