如何使用 JavaScript 限制最小值/最大值之间的数字?

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

How can I use JavaScript to limit a number between a min/max value?

javascriptnumbersinteger

提问by Alexandra

I want to limit a number between two values, I know that in PHP you can do this:

我想限制两个值之间的数字,我知道在 PHP 中你可以这样做:

$number = min(max(intval($number), 1), 20);
// this will make $number 1 if it's lower than 1, and 20 if it's higher than 20

How can I do this in javascript, without having to write multiple ifstatements and stuff like that? Thanks.

我怎样才能在 javascript 中做到这一点,而不必编写多个if语句之类的东西?谢谢。

回答by Govind Malviya

like this

像这样

var number = Math.min(Math.max(parseInt(number), 1), 20);

Live Demo:

现场演示:

function limitNumberWithinRange(num, min, max){
  const MIN = min || 1;
  const MAX = max || 20;
  const parsed = parseInt(num)
  return Math.min(Math.max(parsed, MIN), MAX)
}

alert(
  limitNumberWithinRange(  prompt("enter a number")   )
)

回答by T.J. Crowder

You have at least two options:

你至少有两个选择:

You can use a pair of conditional operators (? :):

您可以使用一对条件运算符 ( ? :):

number = number > 100 ? 100 : number < 0 ? 0 : number;

Or you can combine Math.maxand Math.min:

或者你可以结合Math.maxMath.min

number = Math.min(100, Math.max(0, number));

In both cases, it's relatively easy to confuse yourself, so you might consider having a utility function if you do this in multiple places:

在这两种情况下,比较容易混淆自己,因此如果您在多个地方执行此操作,您可能会考虑使用实用程序函数:

function clamp(val, min, max) {
    return val > max ? max : val < min ? min : val;
}

Then:

然后:

number = clamp(number, 0, 100);

回答by Gregory Bolkenstijn

Use lodash's clampmethod:

使用lodash的clamp方法:

_.clamp(22, 1, 20) // Outputs 20

_.clamp(22, 1, 20) // Outputs 20

回答by Neuron

Needs no further explanation:

无需进一步解释:

function clamp(value, min, max) {
    return Math.min(Math.max(value, min), max);
}

回答by Rafe

Related: What's the most elegant way to cap a number to a segment?:

相关:将数字限制为段的最优雅方法是什么?

Update for ECMAScript 2017:

Math.clamp(x, lower, upper)

But note that as of today, it's a Stage 1 proposal. Until it gets widely supported, you can use a polyfill.

ECMAScript 2017 更新:

Math.clamp(x, lower, upper)

但请注意,截至今天,这是第 1 阶段提案。在它得到广泛支持之前,您可以使用polyfill

回答by ajax333221

I will share my robust function to enforce whole numbers(because of the integertag), it has features like optional min/max parameters and -0protection:

我将分享我的强大功能来强制执行整数(因为integer标签),它具有可选的最小/最大参数和-0保护等功能:

function toInt(val, min, max){
    val=(val*1 || 0);
    val=(val<0 ? Math.ceil(val) : Math.floor(val));

    min*=1;
    max*=1;

    min=((Number.isNaN(min) ? -Infinity : min) || 0);
    max=((Number.isNaN(max) ? Infinity : max) || 0);

    return Math.min(Math.max(val, min), max);
}

Some quick notes:

一些快速说明:

  • The (... || 0)behind the scenes is dealing with -0to change it to 0, which is almost always what you want.
  • The minand maxparameters are optional. When blank or invalid values are passed, they will turn into -Infinityand Infinityso they silently don't interfere with Math.min()and Math.max().
  • You can change Number.isNaN(x)ECMAScript-6 to x!==x(results in true only for NaN) for more compatibility with reallyold browsers, but this is simply not necessarily anymore.
  • (... || 0)幕后进行处理-0,以将其更改为0,这是几乎总是你想要什么。
  • minmax参数都是可选的。当传递空白或无效值时,它们会变成-InfinityandInfinity所以它们不会干扰Math.min()and Math.max()
  • 您可以将Number.isNaN(x)ECMAScript-6更改为x!==x(仅适用于NaN)以获得与真正旧浏览器的更多兼容性,但这不再是必需的。

回答by Femaref

Use Math.minand Math.max.

使用Math.minMath.max