今天翻到了去年比赛的微信小程序,看到了自己的代码的优化过程就分享一下。
backgroundTransformation(weather) {
var that = this
if (weather == "多云") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "阴") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "晴") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "小雨") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "中雨") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "大雨") {
that.setData({
backgroundUrl: ""
})
}
if (weather == "雷阵雨") {
that.setData({
backgroundUrl: ""
})
}
},
这是这段代码最初的样子根据当地天气返回的是一个图片地址。
这是第一次优化的样子
backgroundTransformation(weather) {
var that = this;
switch (weather) {
case "多云":
case "阴":
that.setData({
backgroundUrl: ""
});
break;
case "晴":
that.setData({
backgroundUrl: ""
});
break;
case "小雨":
case "中雨":
case "大雨":
case "雷阵雨":
that.setData({
backgroundUrl: ""
});
break;
default:
break;
}
},
通过switch case优化代码量小了很多,但是感觉还不是很方便,又有了第二次优化
backgroundTransformation(weather) {
const backgroundUrls = {
'多云': '',
'阴': '',
'晴': '',
'小雨': '',
'中雨': '',
'大雨': '',
'雷阵雨': ''
};
this.setData({
backgroundUrl: backgroundUrls[weather] || ''
});
},
这次我把它变成了一个集合,用一个类似kv的形式来选择,这样的话我维护就方便了很多,我直接改集合就好了。
现在思路再开阔一下,我把集合独立出来,变成数据库,这样连代码都不用改了,写过后台管理直接就改好了