猿问

有大佬遇到过这个问题吗:JS获取区间值问题。大佬们有什么好的建议?

switch(voltage){
casevoltage<11.10:
capacity='0'
break;
casevoltage>=11.10&&voltage<11.20:
capacity='5'
break;
casevoltage>=11.20&&voltage<11.30:
capacity='10'
break;
casevoltage>=11.30&&voltage<11.40:
capacity='15'
break;
casevoltage>=11.40&&voltage<11.50:
capacity='20'
break;
casevoltage>=11.50&&voltage<11.60:
capacity='25'
break;
casevoltage>=11.60&&voltage<11.70:
capacity='30'
break;
casevoltage>=11.70&&voltage<11.80:
capacity='35'
break;
casevoltage>=11.80&&voltage<11.90:
capacity='40'
break;
casevoltage>=11.90&&voltage<12.00:
capacity='45'
break;
casevoltage>=12.00&&voltage<12.10:
capacity='50'
break;
casevoltage>=12.10&&voltage<12.20:
capacity='55'
break;
casevoltage>=12.20&&voltage<12.30:
capacity='60'
break;
casevoltage>=12.30&&voltage<12.40:
capacity='65'
break;
casevoltage>=12.40&&voltage<12.50:
capacity='70'
break;
casevoltage>=12.50&&voltage<12.60:
capacity='75'
break;
casevoltage>=12.60&&voltage<12.70:
capacity='80'
break;
casevoltage>=12.70&&voltage<12.80:
capacity='85'
break;
casevoltage>=12.80&&voltage<12.90:
capacity='90'
break;
casevoltage>=12.90&&voltage<13.00:
capacity='95'
break;
casevoltage>=13.00:
capacity='100'
break;
};
现在写法如上,占用了太多空间,请教有没有简短的,或者更好的写法获取区间的值?
Helenr
浏览 334回答 2
2回答

慕慕森

首先我们capacity和voltage是有规律的,即voltage每增长0.1,capacity就会增长5,根据这个规律,可以直接按照公式来计算:functiongetCapacity1(voltage){letcapacityBase=0;letcapacityDiff=5;//增长度为5letvoltageBase=11;if(voltage

素胚勾勒不出你

这样稍微减少一丢丢吧。functionformatVoltage(voltage){if(voltage13){return100}returnparseInt(((parseInt(voltage*10)-111)+1)*5)}console.log(formatVoltage(11.1))//5console.log(formatVoltage(13.1))//100console.log(formatVoltage(12.45665412))//70
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答