如何在 Javascript 中循环使用几个月 [英] How to loop through months in Javascript

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

问题描述

我正在尝试生成一个以月为单位的字符串日期列表(即 [2014 年 10 月"、2014 年 11 月"、...2015 年 1 月"])使用这里的代码:

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 文档指出 setDate 函数设置 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 变量初始化为 Mon Oct 13 2014 00:00:00 GMT-0400(东部夏令时间).当您调用 date.getMonth() 时,它返回 9 表示日历年的第 10 个月;因此,将值增加 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再次,依此类推.由于 while 条件永远不会满足,这种意外行为会继续无休止地重复.

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.

应更新代码以使用 setMonth 代替.

The code should be updated to use setMonth instead.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆