Reputation: 71
I'm using Yahoo Weather and there are about 47 weather conditions from 0 to 47 each number represents the condition of the weather.
I want to get the condition for 4 days , today and the next 3 days so there will be a very long code of switch statements if I use a switch statement for each.
My code now for today condition:
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;
The html:
<img id = 'todayWeatherIcon' />
There are 3 other variables for the next 3 days conditions that will be from 0-47 too and will have the same icons depending on the number.
How to do the same thing for the other 3 variables without repeating the same code?
Upvotes: 0
Views: 54
Reputation: 24247
If the image names are all different then you can best use an array of strings, like this:
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);
Upvotes: 0
Reputation: 1386
You should simply use a function :
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;
...
Upvotes: 0
Reputation: 71
You could just set the condition like so
src = 'condition'+todayCondition+'Img.png';
document.getElementById('todayWeatherIcon').src = src;
Upvotes: 1
Reputation: 2752
there is no need for multiple switch statement, since you have a fixed file name with each weather condition number in the filename you could just do this
var src = "";
// concatenate todayCondition with the rest of the file name
src = "condition" + todayCondition + "Img.png";
document.getElementById('todayWeatherIcon').src = src;
Note: You should only do this if you know the names of the file won't change in the nearest future
Upvotes: 2