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

不使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 15:27:02