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

2022-01-14 00:00:00 numbers integer javascript

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

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

$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

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

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

推荐答案

这样的

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

现场演示:

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

相关文章