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

switch-case中OR运算符失效,如何匹配phone_pe与phonepe?

问题解决方法

你原来的写法case "phone_pe" || "phonepe"是错误的,因为"phone_pe" || "phonepe"会先计算逻辑或表达式,返回第一个真值也就是"phone_pe",所以这个case只会匹配"phone_pe",不会匹配"phonepe"。

有两种可行的修改方式:

方式一:多case共享代码块

直接把两个case写在一起,不添加break,让它们执行同一个逻辑:

try {
    const channeling =
        body?.data?.channel ||
        body?.data_link?.channel;
    switch (channeling) {
        case "phone_pe":
        case "phonepe":
            await phonePeScheduler(body, reqId);
            break;
        case "Gpay":
            await gpayScheduler(body);
            break;
        case "cash":
        default:
            await paymentHandling(body);
    }
} catch (error) {
    // 建议补充异常处理逻辑
}

方式二:提前统一格式

先对channeling做标准化处理(比如移除下划线、转小写),这样后续只需要匹配统一后的字符串:

try {
    // 先标准化格式:移除下划线并转小写
    const rawChannel = body?.data?.channel || body?.data_link?.channel;
    const channeling = rawChannel?.replace('_', '').toLowerCase();
    
    switch (channeling) {
        case "phonepe":
            await phonePeScheduler(body, reqId);
            break;
        case "gpay":
            await gpayScheduler(body);
            break;
        case "cash":
        default:
            await paymentHandling(body);
    }
} catch (error) {
    // 建议补充异常处理逻辑
}

方式一适合固定几个值的场景,写法直接;方式二更灵活,能兼容更多类似的字符串变体(比如"PhonePe"、"PHONE_PE"等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:10:26