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

按时间范围封装数组值:图表X轴1Year月份筛选异常问题

问题修复:1Year筛选选项无法正确显示12个月份

问题根源

你的1Year分支存在两个逻辑错误:

  • numOfMonths = 13:你只需要显示12个完整月份,设置13会多取一个重复月份
  • startMonthIndex = (currentMonth + 11) % 12:这个计算得到的起始索引不符合“过去12个月”的逻辑(比如当前是4月时,会从3月开始取,而不是去年5月)

修复后的代码

public updateXAxisLabels(filter: string): void {
    const currentDate = new Date();
    const currentMonth = currentDate.getMonth();
    const monthNames = [
      'JAN',
      'FEB',
      'MAR',
      'APR',
      'MAY',
      'JUN',
      'JUL',
      'AUG',
      'SEP',
      'OCT',
      'NOV',
      'DEC',
    ];

    let startMonthIndex: number;
    let numOfMonths: number;

    switch (filter) {
      case 'YearToDate':
        startMonthIndex = 0;
        numOfMonths = currentMonth + 1;
        break;
      case '1Month':
        startMonthIndex = currentMonth;
        numOfMonths = 1;
        break;
      case '3Month':
        startMonthIndex = (currentMonth - 2 + 12) % 12;
        numOfMonths = 3;
        break;
      case '6Month':
        startMonthIndex = (currentMonth - 5 + 12) % 12;
        numOfMonths = 6;
        break;
      case '1Year':
        // 计算过去12个月的起始索引:当前月往前推11个月,加12避免负数再取模
        startMonthIndex = (currentMonth - 11 + 12) % 12;
        numOfMonths = 12; // 显示完整12个月
        break;
      default:
        startMonthIndex = 0;
        numOfMonths = currentMonth + 1;
        break;
    }

    const displayedMonthsTemp = [...monthNames, ...monthNames];
    this.displayedMonths = displayedMonthsTemp.slice(
      startMonthIndex,
      startMonthIndex + numOfMonths
    );
  }

逻辑说明

  • 对于1Year选项,(currentMonth - 11 + 12) % 12 确保起始索引始终为非负数,比如当前是4月(索引3),计算后得到(3-11+12)%12=4,对应5月,这样取12个月就是去年5月到今年4月的完整周期。
  • numOfMonths=12 保证只取12个不重复的月份,避免之前多取一个重复月份的问题。

内容的提问来源于stack exchange,提问作者lt-asco

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:57:37