我想知道是否有其他方法可以用更少的代码使此 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/