如何检查数字是否介于两个值之间?

新手上路,请多包涵

在 JavaScript 中,如果窗口大小大于 500 像素,我会告诉浏览器执行某些操作。我这样做:

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

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

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

这在 JavaScript 中甚至可能吗?

原文由 Dyck 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

Tests whether windowsize is greater than 500 and lesser than 600 meaning that neither values 500 or 600 itself will导致条件变为真。

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

原文由 Ram 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 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 小提琴演示

参考:

原文由 David Thomas 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题