如何检查一个数字是否在两个值之间?

2022-08-30 01:47:43

在JavaScript中,我告诉浏览器如果窗口大小大于500px,就做点什么。我是这样做的:

if (windowsize > 500) {
    // do this
}

这很好用,但我想应用相同的方法,但使用一系列数字。所以我想告诉我的浏览器,如果窗口大小在500px和600px之间,那就做点什么。我知道这行不通,但这是我想象的:

if (windowsize > 500-600) {
    // do this
}

在JavaScript中,这有可能吗?


答案 1

检验是否大于和小于意味着值或本身都不会导致条件变为真。windowsize500600500600

if (windowsize > 500 && windowsize < 600) {
  // ...
}

答案 2

我有一会儿,所以,虽然你已经接受了一个答案,但我想我会贡献以下内容:

Number.prototype.between = function(a, b) {
  var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return this > min && this < max;
};

var windowSize = 550;

console.log(windowSize.between(500, 600));

JS 小提琴演示

或者,如果您希望可以选择检查数字是否在定义的范围内,包括端点

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min.apply(Math, [a, b]),
    max = Math.max.apply(Math, [a, b]);
  return inclusive ? this >= min && this <= max : this > min && this < max;
};

var windowSize = 500;

console.log(windowSize.between(500, 603, true));

JS 小提琴演示

编辑以增加对上述内容的微小修改,因为 - 如评论中所述 -

...很慢!此外,当你有固定数量的参数时调用它是毫无意义的......Function.prototype.apply()

值得删除的使用,这产生了上述方法的修订版本,首先没有“包容性”选项:Function.prototype.apply()

Number.prototype.between = function(a, b) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return this > min && this < max;
};

var windowSize = 550;

console.log(windowSize.between(500, 600));

JS 小提琴演示

使用“包容性”选项:

Number.prototype.between = function(a, b, inclusive) {
  var min = Math.min(a, b),
    max = Math.max(a, b);

  return inclusive ? this >= min && this <= max : this > min && this < max;
}

var windowSize = 500;

console.log(windowSize.between(500, 603, true));

JS 小提琴演示

引用: