JavaScript:打印之前的12个月-"3月"打印两次? [英] JavaScript: Print previous 12 months -- "March" prints twice?

查看:36
本文介绍了JavaScript:打印之前的12个月-"3月"打印两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个脚本,以打印前12个月的名称.由于本月是一月,因此应打印:十二月十一月十月九月八月七月六月可能四月行进二月一月

I'm trying to write a script that prints the names of the previous 12 months. Since this month is January, it should print: December November October September August July June May April March February January

相反,它将两次打印3月. http://jsfiddle.net/h69gm04g/2/

Instead, it prints March twice. http://jsfiddle.net/h69gm04g/2/

11月十月九月八月七月六月可能四月行进行进二月

November October September August July June May April March March February

HTML

    <div id="test"></div>

JavaScript

Javascript

    monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
    d = new Date();

    for (i = 0; i < 12; i++) {  
        d.setMonth(d.getMonth() - 1);      
        monthName = monthNames[d.getMonth()];       
        $('#test').append(monthNames[d.getMonth()] + "<br>");       
    }

我在做什么错了?

推荐答案

很好!花了我一段时间.

Nice one! Took me a while.

原因是今天是29日.由于您的日期对象被隐式设置为当前日期,而2013年2月只有28天,因此您看到3月打印了两次.通过设置可选的 day 参数来解决此问题:

The reason for this is that today is the 29th. Since your date object is set to the current day implicitly and February only had 28 days in 2013, you see March printed twice. Fix this by setting the optional day parameter:

d.setMonth(d.getMonth() - 1, 1);

这篇关于JavaScript:打印之前的12个月-"3月"打印两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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