Jquery在数组中获取最近的左右值

时间:2015-01-27 03:14:56

标签: jquery arrays

我有一个阵列 var theArray = [ 1, 3, 8, 10, 13 ];

我想确定数组中用户输入的最近值。 如果用户输入2.它应该显示1作为最接近的值,3显示为最接近的值。

我试过这个

var goal = parseFloat($("#searchbar").val());
        var theArray = [ 1, 3, 8, 10, 13 ];

        $.each(theArray, function(index, value){
             if (closestleft == null || Math.abs(this - goal) < Math.abs(closestleft - goal)) {
            closestleft = this;
          }
        });

        alert(closestleft);

上面的代码将为我提供所需的输出,即1。

问题是我无法获得其他输出3

2 个答案:

答案 0 :(得分:1)

有效。

<script>

        var goal = parseFloat($("#searchbar").val());

        // var goal = 2;
        var closestleft = NaN;
        var closestright = NaN;
        var theArray = [ 1, 3, 8, 10, 13 ];

        $.each(theArray, function(index, value){
           if ((isNaN(closestleft) || Math.abs(this - goal) < Math.abs(closestleft - goal)) && this < goal) closestleft = this;
           if ((isNaN(closestright) || Math.abs(this - goal) < Math.abs(closestright - goal)) && this > goal) closestright = this;
        });

        alert('ClosestLeft = ' + closestleft + ', ClosestRight = ' + closestright);

</script>

答案 1 :(得分:1)

检查一下:

var theArray = [ 1, 3, 8, 10, 13 ];
var userinput = 2;
var left = right= -1;
for(var i in theArray) 
   if(userinput <= theArray[i] && i > 0) {
      left = theArray[i-1];
      right = theArray[i];
      break; 
   }
console.log(right,left);