如何不使用多if-else语句处理对象双Key的多条件判断?
多条件分支的简化方案
你可以通过以下几种方式替代多个独立if语句,让逻辑更清晰易维护:
1. 映射表(对象字面量)方案
把四种状态组合转换成唯一的字符串键,提前定义好每种键对应的处理逻辑,直接通过键取值执行,直观且易扩展:
// 先定义各场景的处理函数 const handlers = { '00': () => { // 都不存在时的操作 return 'both missing'; }, '01': () => { // 仅key2存在时的操作 return 'only key2 present'; }, '10': () => { // 仅key1存在时的操作 return 'only key1 present'; }, '11': () => { // 都存在时的操作 return 'both present'; } }; const getValues = (obj) => { // 将key1、key2的存在状态转为0/1字符串,拼接成唯一键 const statusKey = `${obj.key1 ? '1' : '0'}${obj.key2 ? '1' : '0'}`; // 执行对应逻辑,可选添加默认处理避免键不存在的情况 return handlers[statusKey]?.() || 'invalid status'; }; const obj = { key1: 'key1', key2: '' }; const finalValue = getValues(obj);
2. 数组索引方案
利用二进制转十进制的思路,将四种状态对应到数组的索引位置,逻辑和映射表类似:
const handlers = [ () => 'both missing', // 索引0:都不存在(00) () => 'only key2 present', // 索引1:仅key2存在(01) () => 'only key1 present', // 索引2:仅key1存在(10) () => 'both present' // 索引3:都存在(11) ]; const getValues = (obj) => { // 计算索引:key1对应2^1,key2对应2^0,相加得到0-3的索引 const index = (obj.key1 ? 2 : 0) + (obj.key2 ? 1 : 0); return handlers[index](); }; const obj = { key1: 'key1', key2: '' }; const finalValue = getValues(obj);
3. Switch(true) 方案
如果不想用函数映射,也可以用switch(true)实现互斥分支,比多个独立if更严谨(避免多分支同时执行):
const getValues = (obj) => { const { key1, key2 } = obj; const hasKey1 = !!key1; const hasKey2 = !!key2; switch (true) { case !hasKey1 && !hasKey2: return 'both missing'; case !hasKey1 && hasKey2: return 'only key2 present'; case hasKey1 && !hasKey2: return 'only key1 present'; default: return 'both present'; } }; const obj = { key1: 'key1', key2: '' }; const finalValue = getValues(obj);
注意
原代码的多个独立if未添加return或break,存在多分支执行的风险(比如某个条件满足后,会继续执行后续代码),上述方案都通过return或函数执行确保了分支的互斥性。
内容的提问来源于stack exchange,提问作者TestYellerOP
相关产品推荐
相关产品推荐

