检查数字是否在 JavaScript 范围内的最短代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12806304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:10:18  来源:igfitidea点击:

Shortest code to check if a number is in a range in JavaScript

javascript

提问by Mohsen

This is how I checkout to see if a number is in a range (in between two other numbers):

这是我如何结帐以查看数字是否在一个范围内(在其他两个数字之间):

var a = 10,
    b = 30,
    x = 15,
    y = 35;

x < Math.max(a,b) && x > Math.min(a,b) // -> true
y < Math.max(a,b) && y > Math.min(a,b) // -> false

I have to do this math in my code a lot and I'm looking for shorter equivalent code.

我必须在我的代码中做很多数学运算,我正在寻找更短的等效代码。

This is a shorter version I came up with. But I am sure it can get much shorter:

这是我想出的一个较短的版本。但我相信它可以变得更短:

a < x && x < b
true
a < y && y < b
false

But downside is I have to repeat xor y

但缺点是我必须重复xy

回答by jbabey

Number.prototype.between = function (min, max) {
    return this > min && this < max;
};

if ((5).between(4, 6)) {
    alert('worked!');
}

var num = 6;
if (num.between(5, 7)) {
    alert('still worked!');
}

http://jsfiddle.net/jbabey/4jjRm/1/

http://jsfiddle.net/jbabey/4jjRm/1/

Note that you need to surround number literals in parens, or the interpreter will think your property is a decimal point and blow up.

请注意,您需要将数字文字括在括号中,否则解释器会认为您的属性是小数点并爆炸。

回答by Bill the Lizard

If I had to do this a lot, I'd just write a function inRange(a, b, x)so it would be a short function call any time I needed it. This way you could also make the function body slightly less obfuscated without worrying about its length.

如果我必须经常这样做,我只需编写一个函数,inRange(a, b, x)这样在我需要的任何时候都可以进行简短的函数调用。通过这种方式,您还可以使函数体稍微减少混淆,而不必担心其长度。

回答by MarkT.

If you need the flexibility to test if a number falls between two numbers without first finding the minimum and maximum :

如果您需要灵活地测试一个数字是否介于两个数字之间而无需先找到最小值和最大值:

let inRange = (num1, num2, numTest) => {
  [min, max] = [num1, num2].sort((a, b) => a > b);
  return numTest > min && numTest < max;
}

Testing from low to high:

从低到高测试:

inRange(1, 5, 3); // true
inRange(1, 5, 6); // false

Testing from high to low:

从高到低测试:

inRange(5, 1, 3); // true
inRange(5, 1, 6); // false

回答by adhinna

I edited the code from above, because it doesn't make the sort well. This is what worked for me perfectly (includes the range ends):

我从上面编辑了代码,因为它不能很好地进行排序。这对我来说非常有效(包括范围结束):

var isNumberInRange = (num1, num2, testNum) => {
  var min, max;
  [min, max] = [num1, num2].sort((a, b) => a - b);
  return (testNum >= min && testNum <= max);
};