检查数字是否在javascript范围内

时间:2014-10-28 15:42:47

标签: javascript

JavaScript中是否有内置方式来检查数字是否在另外两个之间?我使用if(x < i && x > l),但希望有更好的解决方案。

3 个答案:

答案 0 :(得分:1)

不会更快或更好地完成它,正如Felix Kling在另一篇文章中所说的那样。

但是,如果你经常使用它,你可以创建一个原型方法:

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

var num = 8;
console.log(num.inRange(7, 8));// true
num = 4;
console.log(num.inRange(7, 8));// false

答案 1 :(得分:0)

  

JavaScript中是否有内置方式来检查数字是否在另外两个之间?

我想你曾想过类似于Python l < x < h的东西。不,没有。
x < h && x > l是内置方式。

答案 2 :(得分:0)

不是内置函数,但没有内置函数没有错误:

function inRange(low, num, high, inclusive) {
  inclusive = (typeof inclusive === "undefined") ? false : inclusive;
  if (inclusive && num >= low && num <= high) return true;
  if (num > low && num < high) return true;
  return false;
}

console.log(inRange(3, 7, 12));      // true
console.log(inRange(3, 7, 7, true)); // true
console.log(inRange(3, 3, 7, true)); // true

console.log(inRange(3, 7, 7));       // false
console.log(inRange(3, 3, 7));       // false
console.log(inRange(3, 9, 7));       // false
console.log(inRange(3, 9, 7, true)); // false