javascript 从2022年05月 生成至当前月份(如果当前日期小于25日则为上月)的一个数组,数组排倒序

 

function generateMonthArray() {
    var startYear = 2023;
    var startMonth = 2; // May is represented by 4 in JavaScript's Date object
    var currentDate = new Date();
    var currentYear = currentDate.getFullYear();
    var currentMonth = currentDate.getMonth();
    var monthArray = [];

    if (currentDate.getDate() < 25) {
        // 当前日期小于25日,为上个月份
        currentMonth -= 1;
        if (currentMonth < 0) {
            // 当前月份为一月时,年份减一
            currentYear -= 1;
            currentMonth = 11; // December is represented by 11
        }
    }

    for (var year = currentYear; year >= startYear; year--) {
        var start = (year === startYear) ? startMonth : 0; // December is represented by 11
        var end = (year === currentYear) ? currentMonth : 11; // December is represented by 11
        debugger;
        for (var month = end; month >= start ; month--) {
            var monthLabel = (month < 9) ? '0' + (month + 1) : (month + 1); // Add leading zero for single-digit months
            var yearMonth = year + '年' + monthLabel + '月';
            monthArray.push({ "Name": yearMonth, "value": yearMonth });
        }
    }

    return monthArray;
}


 // 调用函数生成数组
    var months = generateMonthArray();

 

posted @ 2023-05-17 18:05  三瑞  阅读(52)  评论(0编辑  收藏  举报