按时间范围封装数组值:图表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
相关产品推荐
相关产品推荐

