【发布时间】:2018-07-27 22:08:23
【问题描述】:
我使用的是雅虎天气,大约有 47 种天气状况,从 0 到 47,每个数字代表天气状况。
我想获得 4 天、今天和接下来 3 天的条件,所以如果我为每个使用 switch 语句,将会有很长的 switch 语句代码。
我的代码现在适用于今天的条件:
var src = ""; //This variable will contain an icon that represents the weather condition.
switch(todayCondition){ //todayCondition is today condition it's in the range [0-47]
case "0":
src = 'storm.svg';
break;
........
........
case "47":
src = 'rain.svg';
break;
}
document.getElementById('todayWeatherIcon').src = src;
html:
<img id = 'todayWeatherIcon' />
接下来 3 天的条件还有 3 个其他变量,它们也将在 0-47 之间,并且根据数字具有相同的图标。
如何在不重复相同代码的情况下对其他 3 个变量做同样的事情?
【问题讨论】:
-
你的图标都是
"condition<some number>Img.png"吗?如果是这样,为什么不完全摆脱开关而只做src = "condition" + todayCondition + "Img.png";?然后每天重复一遍。 -
对不起,看来你错过了理解我,我没有解释清楚,图标名称不是“条件”+今天条件+“Img.png”; , 这只是一个指示, 图标就像 cloudy.svg , rain.svg , ...等
-
我会编辑问题
-
@peter,但如果你的“条件”总是从
0..47生成整数,你可以使用var src = arrayOfIconNames[todayCondition];
标签: javascript jquery html switch-statement