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

如何精简JavaScript中的多分支条件判断代码长度?

缩短多分支条件判断的JavaScript代码方案

你可以通过统一遍历目标属性的方式彻底简化这段多分支逻辑,核心思路是把需要检查的属性列成数组,再动态合并存在的数组,避免重复的条件判断。

原代码问题分析

原代码通过大量if-else判断res.data中alley、booked、reminder的存在组合,逻辑重复且冗余,还存在一处逻辑错误:当alley和reminder同时存在时,原代码错误合并了alley和booked而非alley和reminder。

优化后的代码方案

方案1:forEach遍历合并

const targetProps = ['alley', 'booked', 'reminder'];
let getSlotList = [];

targetProps.forEach(prop => {
  if (res.data.hasOwnProperty(prop)) {
    getSlotList = [...getSlotList, ...res.data[prop]];
  }
});

console.log(
  '🚀 ~ file: ScheduleTab.js:66 ~ handleGetSlotsList ~ getSlotList',
  getSlotList,
);

方案2:reduce更简洁写法

const targetProps = ['alley', 'booked', 'reminder'];
const getSlotList = targetProps.reduce((result, prop) => {
  return res.data.hasOwnProperty(prop) ? [...result, ...res.data[prop]] : result;
}, []);

console.log(
  '🚀 ~ file: ScheduleTab.js:66 ~ handleGetSlotsList ~ getSlotList',
  getSlotList,
);

优化说明

  • 把需要检查的属性存入数组targetProps,后续新增或修改属性只需维护这个数组即可,无需修改判断逻辑
  • 自动处理所有属性组合的情况,同时修正了原代码中的逻辑错误
  • 代码量大幅减少,可读性和可维护性显著提升

内容的提问来源于stack exchange,提问作者Prokash Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:00:58