以编程方式确定值是否在给定 N 个范围内的范围内



假设我有一个看起来像这样的数组:

const points = [ .1, .2, .25, .6, .72, .9 ]

这些值中的每一个都表示沿线的点/停靠点。我的目标是有一个函数,它返回输入值落下的范围的索引(两个相邻数组值之间的空间(。

例如,如果我输入.3我的函数将返回3因为.3介于.25.6之间,这是我的数组定义的第 4 个范围。请注意,我认为-infinity.1第一个(隐式(范围。

到目前为止,我已经想出了这个:

function whichRange(input){
if(input < points[0]) {
return 0;
}
else if( input >= points[0] && input < points[1]){
return 1;
}
else if( input >= points[1] && input < points[2]){
return 2;
}
else if( input >= points[2] && input < points[3]){
return 3;
}
else if( input >= points[3] && input < points[4]){
return 4;
}
else if( input >= points[4] && input < points[5]){
return 5;
}
else if (input >= points[5]) {
return 6;
}
}

但是,这假设我的数组中将始终有 6 个停止。

如果我的阵列有n停止怎么办。如何构造类似但更通用的函数?

您可以使用Array#findIndex并检查是否找到索引,然后返回数组的长度。

function getIndex(array, value) {
var index = array.findIndex(v => v >= value);
return index !== -1
? index
: array.length;
}
const points = [.1, .2, .25, .6, .72, .9];
console.log(getIndex(points, .3)); // 3
console.log(getIndex(points, .9)); // 5
console.log(getIndex(points, 1));  // 6

最新更新