不使用if-else/switch,如何根据传入参数获取函数对应返回值
实现方案
完全不需要if-else/switch分支语句,通过对象属性匹配即可实现需求,代码如下:
getDaysInCurrentMonth(type = 'all') { const date = new Date(), month = date.getMonth(), year = date.getFullYear(), days = new Date(year, month, 0).getDate(); const result = { date, month, year, days }; return ({ all: result }[type] ?? result[type]); }
实现逻辑
- 先把所有需要返回的变量统一存入
result对象,方便后续按属性取值 - 构造临时对象
{ all: result }匹配all参数的场景,传入all时直接返回完整的result对象 - 非
all参数的场景下,空值合并运算符??会触发后续取值逻辑,从result中获取对应属性的值返回
如果你的运行环境不支持ES2020的空值合并运算符,也可以替换为逻辑或运算符||,功能一致。
效果验证
- 调用
getDaysInCurrentMonth('days'):直接返回当月天数的数值 - 调用
getDaysInCurrentMonth('all'):返回包含date/month/year/days的完整对象
完全符合预期需求。
内容的提问来源于stack exchange,提问作者Apoorva Chikara
相关产品推荐
相关产品推荐

