Javascript 计算一个数字的范围

Javascript 计算一个数字的范围,javascript,math,Javascript,Math,我想知道一个数字属于哪个范围。我的意思是,假设比例是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 i

我想知道一个数字属于哪个范围。我的意思是,假设比例是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
函数getLocationRange(输入){ 常数切片=4; 常数标度=900; 常量切片=缩放/切片; if(输入<切片){ 返回0; }else if(输入<切片*2){ 返回1; }else if(输入<切片*3){ 返回2; }else if(输入<切片*4){ 返回3; } } getLocationRange(50);//0 getLocationRange(800);//3. getLocationRange(400);//1. 基本上,如果输入的数字进入第一个季度,它将返回0,第二个季度将返回1,以此类推

问题是,这不能扩展,因为我需要为每个片段使用else语句(比如说,我想用6个片段或100个片段来运行它)


有没有一个简单的数学方程式可以达到同样的效果?(不要担心负值或大于或等于刻度。)

关于如何从代码中得出这个答案的一点解释:在您的条件下,将两边除以
切片。使用
const x=input/slice现在有:
if(x<1){return 0;}else if(x<2){return 1)else if(x<3){return 2;}…
等。在每种情况下,
x
都被转换成(返回值)最接近的小于或等于
x
的整数。这正是
Math.floor(x)
所做的。
getRange(input, scale, slices) {
    return Math.floor(input / (scale / slices));
}