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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14718561/
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-08-24 17:44:19  来源:igfitidea点击:

How to check if a number is between two values?

javascript

提问by Dyck

In JavaScript, I'm telling the browser to do something if the window size is greater than 500px. I do it like so:

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

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

This works great, but I would like to apply this same method, but with a range of numbers. So I would like to tell my browser to do stuff if the window size is between 500px and 600px. I know this wouldn't work, but here is how I imagined it:

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

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

Is this even possible, within JavaScript?

在 JavaScript 中,这甚至可能吗?

回答by undefined

Tests whether windowsizeis greater than 500and lesser than 600meaning that neither values 500or 600itself will result in the condition becoming true.

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

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

回答by David says reinstate Monica

I had a moment, so, although you've already accepted an answer, I thought I'd contribute the following:

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

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 Fiddle demo.

JS小提琴演示

Or, if you'd prefer to have the option to check a number is in the defined range including the end-points:

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

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 Fiddle demo.

JS小提琴演示

Edited to add a minor amendment to the above, given that – as noted in the comments –

鉴于 - 如评论中所述 -

Function.prototype.apply()is slow! Besides calling it when you have a fixed amount of arguments is pointless…

……Function.prototype.apply()很慢!除了当你有固定数量的参数时调用它是没有意义的......

it was worth removing the use of Function.prototype.apply(), which yields the amended versions of the above methods, firstly without the 'inclusive' option:

值得删除的使用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 Fiddle demo.

JS小提琴演示

And with the 'inclusive' option:

并使用“包含”选项:

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 Fiddle demo.

JS小提琴演示

References:

参考:

回答by David

I prefer to put the variable on the inside to give an extra hint that the code is validating my variable is between a range values

我更喜欢将变量放在里面,以给出一个额外的提示,即代码正在验证我的变量是否在一个范围值之间

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

回答by antongorodezkiy

It's an old question, however might be useful for someone like me.

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

lodashhas _.inRange()function https://lodash.com/docs/4.17.4#inRange

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

Example:

例子:

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

Please note that this method utilizes the Lodashutility library, and requires access to an installed version of Lodash.

请注意,此方法使用Lodash实用程序库,并且需要访问已安装的 Lodash 版本。

回答by Hanzla Habib

You can use Multiple clause in ifcondition instead of writing

您可以在if条件中使用 Multiple 子句而不是编写

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

because this really makes no sense logically JavaScript will read your if condition like

因为这在逻辑上确实没有意义 JavaScript 会读取您的 if 条件,例如

windowSize > -100 

because it calculates 500-600to -100

因为它计算500-600-100

You should use &&for strict checking both cases for example which will look like this

您应该使用&&严格检查这两种情况,例如看起来像这样

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

// Then doo something

}

回答by yukashima huksay

Here is the shortest method possible:

这是可能的最短方法:

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

Parametrized:

参数化:

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

You can divide both sides by 2 if you don't understand how the first one works;)

如果您不了解第一个是如何工作的,您可以将两边除以 2;)

回答by WiseGuy

I just implemented this bit of jQuery to show and hide bootstrap modal values. Different fields are displayed based on the value range of a users textbox entry.

我刚刚实现了这一点 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();
                }
            }
    });