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

TypeScript实现月份选择时如何精简冗余if/else代码

TypeScript月份选择逻辑精简优化方案

核心问题分析

原代码的冗余来自两处:

  • 外层if/else两个分支的执行逻辑完全一致,仅依赖的月份数据源(allMonths/currentYearMonths)不同,相同的选项映射、选中值校验逻辑重复写了两遍
  • 选中值校验用了两层嵌套if,判断条件可以合并,减少不必要的代码层级

优化方案

核心思路是提前抽离分支差异点,复用公共逻辑:先根据年份判断选出当前场景下生效的可用月份列表,后续所有操作都基于这个统一的数据源执行,彻底消除重复代码和冗余嵌套。
优化后代码:

// 按年份规则确定当前可选择的月份集合
const availableMonths = newYear < this.currentYear ? this.allMonths : this.currentYearMonths;
// 统一生成月份选项
this.months = availableMonths.map(value => ({ value, label: value }));
// 校验已选月份是否在可选范围内,不在则清空
if (this.selectedMonth && !availableMonths.includes(this.selectedMonth)) {
  this.selectedMonth = undefined;
}

额外逻辑隐患修复

原代码的选中值判断存在隐性bug:如果月份值采用JS Date默认的数字规则(0代表1月,取值范围0-11),数字0会被if (this.selectedMonth)判定为假值,导致选中1月(值为0)时不会走合法性校验。
建议将判断条件改为明确判断非undefined,逻辑更严谨:

const availableMonths = newYear < this.currentYear ? this.allMonths : this.currentYearMonths;
this.months = availableMonths.map(value => ({ value, label: value }));
if (this.selectedMonth !== undefined && !availableMonths.includes(this.selectedMonth)) {
  this.selectedMonth = undefined;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 03:39:30