还有其他方法可以减少 if-else 语句吗?此代码将通过从数据库获取整数来更改图片。我尝试减少这段代码。
if (val["soil_h"] < 21){
$("#ground").attr('src', 'pic/ground1.png');
} else if (val["soil_h"] < 42){
$("#ground").attr('src', 'pic/ground2.png');
} else if (val["soil_h"] < 63){
$("#ground").attr('src', 'pic/ground3.png');
} else if (val["soil_h"] < 84){
$("#ground").attr('src', 'pic/ground4.png');
} else if (val["soil_h"] < 105){
$("#ground").attr('src', 'pic/ground5.png');
} else if (val["soil_h"] < 126){
$("#ground").attr('src', 'pic/ground6.png');
} else if (val["soil_h"] < 147){
$("#ground").attr('src', 'pic/ground7.png');
} else {
$("$ground").attr('src', 'pic/ground8.png');
}
最佳答案
Use
/
(division) as all the values are multiple of21
试试这个:
var value=val["soil_h"]/21;
$("#ground").attr('src', 'pic/ground"'+(value % 1 === 0 ? value : 8)+'".png'); //If value is not multiple of 21, default image is set..
关于javascript - 如何减少 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35721990/