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
相关产品推荐
相关产品推荐

