[英]How to use switch with more than one variable?
我使用的是Yahoo Weather,大約有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個變量執行相同操作?
不需要多個switch語句,因為您有一個固定的文件名,文件名中有每個天氣狀況編號,您可以這樣做
var src = "";
// concatenate todayCondition with the rest of the file name
src = "condition" + todayCondition + "Img.png";
document.getElementById('todayWeatherIcon').src = src;
注意 :僅當您知道文件名在最近的將來不會更改時,才應該這樣做
您可以像這樣設置條件
src = 'condition'+todayCondition+'Img.png'; document.getElementById('todayWeatherIcon').src = src;
您應該只使用一個函數:
function getIcon(weatherCondition)
{
var src = ""; //This variable will contain an icon that represents the weather condition.
switch(weatherCondition){ //weatherCondition is the weather condition it's in the range [0-47]
case "0":
src = 'storm.svg';
break;
........
........
case "47":
src = 'rain.svg';
break;
}
return src;
}
var day1Condition = getIcon(todayCondition);
var day2Condition = getIcon(tomorrowCondition);
...
document.getElementById('todayWeatherIcon').src = day1Condition;
document.getElementById('tomorrowWeatherIcon').src = day2Condition;
...
如果圖像名稱都不同,那么最好使用字符串數組,如下所示:
var images = ["cloudy.svg", "sunny.svg", "rainy.svg"]; // Arrays are designed to work with numeric index values: console.log(images[0]); console.log(images[1]); console.log(images[2]); console.log("--------------") // Javascript also accepts "numeric strings" as array index values: console.log(images["0"]); console.log(images["2"]); console.log("--------------") // Or using a variable, this is the closest to what you need to do: var todayCondition = "1"; var src = images[todayCondition]; console.log(src);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.