假设我有一个看起来像这样的数组:
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
,该怎么办呢?如何构造类似但更通用的功能?
答案 0 :(得分:5)