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

问题描述 投票:0回答:13

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

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

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

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

在 JavaScript 中这甚至可能吗?

javascript
13个回答
288
投票

测试

windowsize
是否大于
500
和小于
600
意味着无论是值
500
还是
600
本身都不会导致条件变为真。

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

147
投票

我有时间,所以,尽管您已经接受了答案,但我想我会做出以下贡献:

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

参考资料:


111
投票

我更喜欢将变量放在内部,以额外提示代码正在验证我的变量在范围值之间

if (500 < size && size < 600) { doStuff(); }

35
投票

这是一个老问题,但可能对像我这样的人有用。

lodash
具有
_.inRange()
功能https://lodash.com/docs/4.17.4#inRange

例子:

_.inRange(3, 2, 4);
// => true

请注意,此方法使用

Lodash
实用程序库,并且需要访问已安装的 Lodash 版本。


7
投票

你可以简单地做

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

或者如果你想要干净的代码你可以在任何公共地方的主js文件中编写自己的函数。

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;
};

然后你可以这样称呼它

if(windowsize.between(500, 600)){
 //your logic
}

4
投票

您可以在

if
条件中使用Multiple从句而不是写

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

因为这真的没有意义 逻辑上 JavaScript 会像

一样读取你的 if 条件
windowSize > -100 

因为它计算

500-600
-100

你应该使用

&&
来严格检查这两种情况,例如它看起来像这样

if( windowSize > 500 && windowSize < 600 ){

// Then doo something

}

4
投票

这是一个通用的方法,你可以到处使用

const isBetween = (num1,num2,value) => value > num1 && value < num2 

3
投票

这是最短的方法:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

参数化:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

如果你不明白第一个是如何工作的,你可以把两边都除以2;)


3
投票

我知道有一个公认的答案,但我想提供一些在某些情况下有用的方法。如果我们想检查

n
是否在
x
y
之间,我们可以这样做:

x <= n && n <= y
(x - n) * (y - n) <= 0

第二个非常有用,当你试图获得相同的结果,即使你交换

x
y


0
投票

我刚刚实现了这个 jQuery 来显示和隐藏引导模式值。根据用户文本框条目的值范围显示不同的字段。

$(document).ready(function () {
    jQuery.noConflict();
    var Ammount = document.getElementById('Ammount');

    $("#addtocart").click(function () {

            if ($(Ammount).val() >= 250 && $(Ammount).val() <= 499) {
                {
                    $('#myModal').modal();
                    $("#myModalLabelbronze").show();
                    $("#myModalLabelsilver").hide();
                    $("#myModalLabelgold").hide();
                    $("#myModalPbronze").show();
                    $("#myModalPSilver").hide();
                    $("#myModalPGold").hide();
                }
            }
    });

0
投票

就像大卫的回答一样,但我需要包含 a 或 b。所以我的解决方案:

export const between = (num: number, a: number, b: number, inclusiveA = true, inclusiveB = true): boolean => {
  if (a > b) [a, b, inclusiveA, inclusiveB] = [b, a, inclusiveB, inclusiveA];
  if (a == b && (inclusiveA || inclusiveB)) [inclusiveA, inclusiveB] = [true, true];
  return (inclusiveA ? num >= a : num > a) && (inclusiveB ? num <= b : num < b);
};

if (require.main === module) {
  console.log(between(12, 15, 10)); //true
  console.log(between(15, 15, 10)); //true
  console.log(between(15, 10, 15)); //true
  console.log(between(10, 10, 15, false)); //false
  console.log(between(15, 10, 10, true, false)); //false
  
  //edge case: if a==b then enough that either of the edges is inclusive
  console.log(between(10, 10, 10, true, false)); //true
}

它也是 typescript 而不是 javascript


0
投票

  function handleBetween(number, calc) {
        let [a, b] = calc;
        let min = Math.min(a, b), max = Math.max(a, b);
        return number > min && number < max;
    }

    if(510 >500 && 510 <600){
    console.log(`510 >500 && 510 <600 is true`)
    }


    if(610 >500 && 610 <600){
    // false
    console.log(`610 >500 && 610 <600 is true`)
    } else console.log(`610 >500 && 610 <600 is false`)


    
     console.log(handleBetween(510, [500, 600])); // true
     console.log(handleBetween(610, [500, 600])); // false


-1
投票

你可以用这个例如:

if (windowsize > 500 || windowsize < 600) {
    // do this
}
© www.soinside.com 2019 - 2024. All rights reserved.