我正在使用雅虎天气,大约有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个变量做同样的事情?
答案 0 :(得分:2)
不需要多个switch语句,因为你有一个固定的文件名,文件名中的每个天气条件号都可以这样做
var src = "";
// concatenate todayCondition with the rest of the file name
src = "condition" + todayCondition + "Img.png";
document.getElementById('todayWeatherIcon').src = src;
注意:只有在知道文件名称在不久的将来不会改变时才应该这样做
答案 1 :(得分:1)
您可以像这样设置条件
render() {
// If loading, render activity indicator
if (this.props.isLoadingPosts) {
return (
<View style={commonStyles.center}>
<ActivityIndicator />
</View>
);
}
// Otherwise render posts
return (
<View>
<FlatList
style={styles.fullHeight}
data={this.props.data}
extraData={this.props.loadingMore}
keyboardShouldPersistTaps='always'
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={this.renderSeparator}
ListFooterComponent={this.renderFooter}
refreshing={this.props.refreshing}
onRefresh={this.onRefresh}
onEndReached={this.onEndReached}
onEndReachedThreshold={0.5}
renderItem={({ item }) => (
<ListItem
item={item}
onPressItem={() => this.showPost(item)}
navigator={this.props.navigator}
/>
)}
/>
</View>
);
}
答案 2 :(得分:0)
您应该只使用一个功能:
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;
...
答案 3 :(得分:0)
如果图像名称都不同,那么最好使用字符串数组,如下所示:
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);