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

时间:2022-09-26 21:21:45

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语句和类似的东西?谢谢。

3 个解决方案

#1


77  

like this

喜欢这个

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

#2


1  

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

#3


0  

Use Math.min and Math.max.

使用Math.min和Math.max。

#1


77  

like this

喜欢这个

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

#2


1  

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

#3


0  

Use Math.min and Math.max.

使用Math.min和Math.max。