我可以在switch语句上使用对象吗?

问题描述 投票:0回答:1

我想知道是否有另一种方法可以用更少的代码来提高此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;
      }
javascript ajax switch-statement javascript-objects
1个回答
0
投票

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

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" />`;

0
投票

每个天气状况都有三个与之关联的唯一字符串:API返回的字符串,图像文件名和图像alt。您可以使用由API响应字符串索引的对象来简洁地执行此操作,其中每个值可以是另一个对象或数组:

const weatherStrings = {
  Cloud: ['cloud', 'cloud',
  Hail: ['hail', 'hail'],
  'Heavy Cloud': ['heavy cloud', 'heavy-clouds'],
  // ...
}

// ...

success: function(response) {
  for (const item of response.weather) {
    const [filename, alt] = weatherStrings[item.currentConditions];
    const icon = `<img src="./weather_icons/${filename}.png" alt="${alt}" width="22px">`;
    // ...
  }
© www.soinside.com 2019 - 2024. All rights reserved.