javascript - 我可以在 Switch 语句上使用对象吗?

标签 javascript ajax switch-statement javascript-objects

我想知道是否有其他方法可以用更少的代码使此 Switch 语句更高效?

我听说对象更好、更干净,并且不再需要使用中断。我该如何正确使用它?

谢谢。

此处代码 - https://jsfiddle.net/lmanhaes/cq1g5dyt/4/

$.each(response.weather, function(index) { //retrieve data
      let icon;
      switch (response.weather[index].currentConditions) { //switch case for icons
        case "Cloud":
          icon = '<img src="./weather_icons/cloud.png" alt="cloud" width="22px"/>';
          break;
        case "Hail":
          icon = '<img src="./weather_icons/hail.png" alt="hail" width="22px"/>';
          break;
        case "Heavy Cloud":
          icon = '<img src="./weather_icons/heavy cloud.png" alt="heavy-clouds" width="22px"/>';
          break;
        case "Heavy Rain":
          icon = '<img src="./weather_icons/heavy rain.png" alt="heavy-rain" width="22px"/>';
          break;
        case "Rain":
          icon = '<img src="./weather_icons/rain.png" alt="rain" width="22px"/>';
          break;
        case "Sleet":
          icon = '<img src="./weather_icons/sleet.png" alt="sleet" width="22px"/>';
          break;
        case "Snow":
          icon = '<img src="./weather_icons/snow.png" alt="snow" width="22px"/>';
          break;
        case "Sun":
          icon = '<img src="./weather_icons/sun.png" alt="sun" width="22px"/>';
          break;
        case "Sun and Clouds":
          icon = '<img src="./weather_icons/sun and cloud.png" alt="sun-clouds" width="22px"/>';
          break
        case "Thunderstorm":
          icon = '<img src="./weather_icons/thunderstorm.png" alt="thunderstorm" width="22px"/>';
          break;
      }

最佳答案

当然。您可以构建天气类型字典。

/** @typedef {{file: string, label: string}} WeatherEntry */
/** @typedef {[key: string]: WeatherEntry} WeatherMap */

/** @type {WeatherMap} */
const weather = {
    "Cloud": {
        "file": "cloud.png",
        "label": "cloud"
    },
    // ...
};

然后使用它:

const entry = weather[response.weather[index].currentConditions];
let icon = `<img src="./weather_icons/${entry.file}" alt="${entry.label}" width="22px" />`;

关于javascript - 我可以在 Switch 语句上使用对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60717091/

相关文章:

javascript - jquery 触摸导航

javascript - 返回函数表达式而不是结果

php - 如何在发布后保留表单值

javascript - Asp.Net - 如果未启用 JavaScript,则重定向

php - ajax搜索如何检查某个短语是否包含搜索的单词

php - 通过 PHP 在 FTP 服务器上检查没有扩展名的文件的文件大小?

c - 在 C 中使用用户输入的字符串从一个函数到另一个函数

将 ada 代码转换为其 C

c++ - 切换枚举时在 switch 语句中使用默认值

javascript - 如何清除/重置react.js表单中的输入数据?