You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何生成含当前月份的图表近12个月数据模板

问题描述

需要生成包含当前月份在内的近12个月数据模板,示例模板结构如下:

[{id: BAD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
{id: GOOD,
data: [
{
x: "11",
y: 0
},
{
x: "12",
y: 0
},
{
x: "1",
y: 0
},
...
]},
... 
]

目前遇到的问题:当月份递增到12后,生成的x值会持续增大,无法正确循环为1、2等月份数字。尝试的代码如下:

const NUMBER_OF_MONTHS = 12;

const getFirstMonth = (date, numOfMonths) => {
   date.setMonth(date.getMonth() - numOfMonths);
    return date.getMonth();
}

const createDataTemplate = () => {
    const template = [];
    const firstMonth = getFirstMonth(new Date(), NUMBER_OF_MONTHS)

    for (let i = 0; i < RATINGS.length; i++) {
        template.push({
            'id': RATINGS[i],
            'data': []
        })
        for (let j = 1; j <= NUMBER_OF_MONTHS; j++) {
            template[i].data.push({
                'x': `${firstMonth + j}`,
                'y': 0
            })
        }
    }

    return template;
}
解决思路

核心问题分析

原代码的问题在于:

  • JavaScript的Date.getMonth()返回0-11的数字(0代表1月,11代表12月),直接用firstMonth + j计算会超出11,得到12、13等无效月份值;
  • 手动计算月份数值没有处理跨年的循环逻辑,导致无法自动从12月回到1月。

修正方案

利用JavaScriptDate对象的自动月份溢出处理特性,逐个生成近12个月的日期,再提取对应的1-12格式月份数字:

  1. 从当前日期开始,依次往前推到第12个月的起始点;
  2. 循环12次,每次给日期加1个月,然后提取月份数字(getMonth() + 1,转换为1-12的格式);
  3. 为每个RATINGS条目生成对应的data数组。

修正后的代码

const NUMBER_OF_MONTHS = 12;
// 假设RATINGS是已定义的数组,比如['BAD', 'GOOD', ...]

const createDataTemplate = () => {
    const template = [];
    // 初始化起始日期:当前日期往前推11个月(包含当前月,共12个月)
    const currentDate = new Date();
    const startDate = new Date(currentDate);
    startDate.setMonth(currentDate.getMonth() - (NUMBER_OF_MONTHS - 1));

    for (const rating of RATINGS) {
        const dataPoints = [];
        const tempDate = new Date(startDate);
        
        for (let i = 0; i < NUMBER_OF_MONTHS; i++) {
            // 转换为1-12的月份数字,转成字符串
            const monthNum = tempDate.getMonth() + 1;
            dataPoints.push({
                x: `${monthNum}`,
                y: 0
            });
            // Date会自动处理跨年/跨月的溢出逻辑
            tempDate.setMonth(tempDate.getMonth() + 1);
        }

        template.push({
            id: rating,
            data: dataPoints
        });
    }

    return template;
}

关键说明

  • 用startDate设置为当前月往前推11个月,确保循环12次后刚好包含当前月;
  • 每次循环通过tempDate.setMonth()自动处理月份溢出(比如12月加1个月会自动跳到次年1月);
  • 用tempDate.getMonth() + 1将0基的月份转换为1-12的实际月份数字,再转成字符串作为x的值。

内容的提问来源于stack exchange,提问作者Mefju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:51:16