如何优化JavaScript条件判断中的多OR运算符比较语法?
优化多值判断的if-else语法思路
嘿,这个问题提得很实在——一堆||堆在一起不仅写着麻烦,后期维护也容易漏改。针对你这个场景,不用switch的话,有几个非常实用的优化方向,让代码更简洁清晰:
1. 用数组includes()替代多OR判断
把每个条件对应的有效值放进数组,用includes()方法判断变量是否在数组内,语法直观简洁,可读性拉满:
function cc(card) { // Only change code below this line if ([2, 3, 4, 5, 6].includes(card)) { count += 1; } else if ([7, 8, 9].includes(card)) { count += 0; } else if ([10, "J", "Q", "K", "A"].includes(card)) { count -= 1; } else { return "No such combination"; } return count > 0 ? `${count} Bet` : `${count} Hold`; // Only change code above this line }
这种方式的好处是:新增或修改有效值时,直接修改数组元素就行,不用调整逻辑运算符,出错概率更低。
2. 用对象映射表统一处理逻辑
如果你的判断逻辑是**“不同输入对应不同操作/值”**,用对象做映射表是更优雅的选择——把card值作为键,对应的count变化量作为值,直接通过键值对获取操作,彻底告别嵌套if-else:
function cc(card) { // Only change code below this line const cardActionMap = { 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 0, 8: 0, 9: 0, 10: -1, J: -1, Q: -1, K: -1, A: -1 }; // 判断card是否在映射表中 if (cardActionMap.hasOwnProperty(card)) { count += cardActionMap[card]; } else { return "No such combination"; } return count > 0 ? `${count} Bet` : `${count} Hold`; // Only change code above this line }
这种方式的优势在于:逻辑和数据分离,后期要新增card类型(比如新增 Joker 对应-2),只需要在映射表里加一行就行,完全不用动判断逻辑,扩展性极强。
3. 结合范围判断进一步简化(针对数字类型)
因为你的数字card有明确的范围区间(2-6、7-9),可以针对数字类型单独做范围判断,剩下的字符串类型再用includes处理,减少数组的长度:
function cc(card) { // Only change code below this line if (typeof card === 'number') { if (card >= 2 && card <= 6) { count += 1; } else if (card >=7 && card <=9) { count +=0; } else if (card ===10) { count -=1; } else { return "No such combination"; } } else if (["J", "Q", "K", "A"].includes(card)) { count -=1; } else { return "No such combination"; } return count > 0 ? `${count} Bet` : `${count} Hold`; // Only change code above this line }
这种方式适合数字有连续范围、字符串是离散值的场景,能进一步减少判断的复杂度。
另外,最后返回的部分用模板字符串和三元运算符简化,比拼接字符串更清爽哦~
内容的提问来源于stack exchange,提问作者NBash




