在给定N个范围的情况下,以编程方式确定值是否在一个范围内

Wil*_*llD 2 javascript

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

const points = [ .1, .2, .25, .6, .72, .9 ]
Run Code Online (Sandbox Code Playgroud)

这些值中的每一个都代表一条线上的点/停止点。我的目标是要有一个函数,该函数返回输入值所在的范围(两个相邻数组值之间的空间)的索引。

例如,如果我放入.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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这假设我在数组中始终总是有6个停靠点。

如果我的阵列n停了怎么办。如何构造类似但更通用的功能?

Nin*_*olz 5

您可以使用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
Run Code Online (Sandbox Code Playgroud)