简体   繁体   English

获得最接近的价值

[英]Getting the closest value

I've come across this problem a few times now and I don't have a nice solution for it. 我已经遇到过几次这个问题,但是我没有很好的解决方案。

Suppose I have a simple array of numbers at non-fixed intervals, myArray . 假设我有一个不固定间隔的简单数字数组myArray I would like to have a function that can take a whole number (it could be negative) and return the value in the array that it is closest to. 我想要一个可以取整数(可以为负)并返回最接近的数组中的值的函数。 In my example, I'd like it to return 850 . 在我的示例中,我希望它返回850

I think I need to use the upper and lower variables to work out which of the array values is closest to the value I pass in. 我想我需要使用upperlower变量制定出该数组值是最接近我传递值。

Am I on the right track or is there a more efficient way of achieving this and could anyone give me a nudge in the right direction? 我是在正确的道路上吗?还是有更有效的方法来实现这一目标?有人可以向我推一下正确的方向吗?

Here is what I have so far: 这是我到目前为止的内容:

var myArray = [0,850,1800,2500,3300];

function snapTo(value){
    var upper = -1;
    var lower = -1;

    // if the value is bigger than the last array value
    if(value > myArray[myArray.length-1]){
        upper = myArray[myArray.length-1];
        lower = myArray[myArray.length-2];
    // if the value is smaller than the first array value
    } else if(value < myArray[0]){
        upper = myArray[1];
        lower = myArray[0];
    } else {
        for(var i = 0, i < myArray.length, i++){
            if(value > myArray[i]){
                upper = myArray[i];
                lower = myArray[i-1];
                break;
            }
        }
    }

    // x being the index of the closest array value to the one passed in
    return myArray[x];
}

snapTo(1200);

您的先生正在寻找二进制搜索而不是!

I would give you the nudge that you don't specifically need to check whether the value is larger or smaller than the previous array value. 我想告诉您,您不需要特别检查该值是大于还是小于先前的数组值。 Instead just work out the absolute difference between your target value and the "current" array element. 相反,只需计算出目标值和“当前”数组元素之间的绝对差即可。 And compare it to the best difference so far to decide whether this array index is the winning candidate so far... 并将其与迄今为止的最佳差异进行比较,以确定此数组索引是否是迄今为止的获胜者...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM