2

假设我有一个如下所示的数组:

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停靠点怎么办。如何构建一个类似但更通用的函数?

4

1 回答 1

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

于 2019-08-13T17:15:24.130 回答