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

JavaScript中Switch语句直接进入default分支问题排查

问题原因

findByCode函数没有定义返回值,当前函数仅通过console.log打印了匹配到的天气类型,没有将结果向外返回,函数实际执行后返回的是undefined,因此switch语句拿不到对应的天气类型字符串,永远进入default分支。

修复方案

调整findByCode函数,将匹配结果返回即可。如果需要保留控制台打印逻辑,可以先存储匹配结果,打印后再返回:

const findByCode = (code) => {
    const matchedWeather = Object.keys(weatherConditions).find((key) => {
        return weatherConditions[key].includes(code);
    });
    console.log(matchedWeather);
    return matchedWeather;
};

如果不需要打印逻辑,可以简化写法:

const findByCode = (code) => Object.keys(weatherConditions).find(key => weatherConditions[key].includes(code));
补充注意

如果修改后仍匹配失败,检查API返回的weatherCode类型:若接口返回的是字符串格式的状态码(例如"113"而非数字113),由于includes是严格相等匹配,字符串和数字不会被判定为相等,这种情况需要先把入参转为数字再做匹配:

const findByCode = (code) => {
    const targetCode = Number(code);
    return Object.keys(weatherConditions).find(key => weatherConditions[key].includes(targetCode));
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:12:25