我想知道一个数字属于哪个范围.我的意思是,假设比例是900,我们将其分成4个区域.
function getLocationRange(input){
const slices = 4;
const scale = 900;
const slice = scale / slices;
if(input < slice){
return 0;
} else if (input < slice * 2) {
return 1;
} else if (input < slice * 3) {
return 2;
} else if (input < slice * 4) {
return 3;
}
}
getLocationRange(50); // 0
getLocationRange(800); // 3
getLocationRange(400); // 1
Run Code Online (Sandbox Code Playgroud)
基本上如果输入数字落在第一季度它返回0,第二季度返回1,等等......
麻烦的是,这不会扩展,因为我需要每个切片的其他语句(假设我想用6个切片或100个切片来运行它).
是否有一个简单的数学方程式来达到同样的效果?(不要担心负面或大于或等于比例.)
小智 5
getRange(input, scale, slices) {
return Math.floor(input / (scale / slices));
}
Run Code Online (Sandbox Code Playgroud)