如何使用 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
How can I use JavaScript to limit a number between a min/max value?
提问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 if
statements 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.max
and Math.min
:
或者你可以结合Math.max
和Math.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
回答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)
回答by ajax333221
I will share my robust function to enforce whole numbers(because of the integer
tag), it has features like optional min/max parameters and -0
protection:
我将分享我的强大功能来强制执行整数(因为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-0
to change it to0
, which is almost always what you want. - The
min
andmax
parameters are optional. When blank or invalid values are passed, they will turn into-Infinity
andInfinity
so they silently don't interfere withMath.min()
andMath.max()
. - You can change
Number.isNaN(x)
ECMAScript-6 tox!==x
(results in true only forNaN
) for more compatibility with reallyold browsers, but this is simply not necessarily anymore.
- 在
(... || 0)
幕后进行处理-0
,以将其更改为0
,这是几乎总是你想要什么。 - 在
min
和max
参数都是可选的。当传递空白或无效值时,它们会变成-Infinity
andInfinity
所以它们不会干扰Math.min()
andMath.max()
。 - 您可以将
Number.isNaN(x)
ECMAScript-6更改为x!==x
(仅适用于NaN
)以获得与真正旧浏览器的更多兼容性,但这不再是必需的。
回答by Femaref
Use Math.min
and Math.max
.
使用Math.min
和Math.max
。