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

前端 未结 7 1159
醉梦人生
醉梦人生 2020-12-04 16:15

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 i         


        
7条回答
  •  孤城傲影
    2020-12-04 16:41

    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.

提交回复
热议问题