且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-04 08:44:13

喜欢这个

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


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

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

like this

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