问题描述:

What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?

网友答案:

There is no specific function, but you can do it like this:

lowNumber < yourNumber && yourNumber < highNumber
网友答案:

Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:

Number.prototype.inRange = function( a,b ) {
    var n = +this;
    return ( n > a && n < b );
};

So you'd use it like this:

(5).inRange( 3, 7 ); // true

Example: http://jsfiddle.net/dTHQ3/

网友答案:

Um if it is greater than one and less than the other.

var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
网友答案:
if ( yournumber < highNumber && yournumber > lowNumber ){    
  // do something    
} else {    
  // do something else    
}
网友答案:

The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?

With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.

Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.

相关阅读:
Top