获取JavaScript的最后n个季度

时间:2016-01-06 01:42:50

标签: javascript loops offset

显然,this kind of question was asked before,但这是一个C#答案,我无法翻译成JavaScript。

这是我的原始代码,但现在第一季度失败了:

var amount = 6;
var now = new Date();
var thisYear = now.getFullYear();
var quarterStart = Math.ceil((now.getMonth() + 1) / 3);
//quarterStart will return a number between 1 and 4

for (var i = 0; i < amount; i++) {

    //here's the line that definitely needs to be changed
    var thisQuarter = quarterStart - (i % 4);

    //if thisQuarter is the last one, go back one year
    if (thisQuarter == 4 && i > 0) {
        thisYear--;
    };

    console.log('Q' + thisQuarter + ' ' + thisYear);
};

//console should return the following
//'Q1 2016'
//'Q4 2015'
//'Q3 2015'
//'Q2 2015'
//'Q1 2015'
//'Q4 2014'

编辑:只要输出如图所示,就可以改变循环的设置。

1 个答案:

答案 0 :(得分:3)

我已对您的代码进行了一些更改,现在应该正常工作。

var amount = 6;
var now = new Date();
var thisYear = now.getFullYear();
var quarterStart = Math.ceil((now.getMonth() + 1) / 3);

for (var i = 0; i < amount; i++) {
    console.log('Q' + quarterStart + ' ' + thisYear);

    quarterStart--;
    if (quarterStart <= 0) {
        thisYear--;
        quarterStart = 4;
    };
};