Javascript min max

In PHP, you can use this to keep the number between two values, minimum and maximum:

$n = min(max($n, 1), 20);

therefore, if $ n is greater than 20, it will take the value 20. If it is less than 1, it will take the value 1. Otherwise, it will not change

How to do this in javascript / jQuery?

+6
source share
4 answers

This is almost the same in JavaScript, only those min and max are members of the Math object:

 var n = Math.min(Math.max(n, 1), 20); 
+11
source

JavaScript Math.min [MDN] and Math.max [MDN] .

Alternatively, you can use the conditional operator:

 n = n > 20 ? 20 : (n < 1 ? 1 : n) 
+6
source

You can do this with min and max, but I think if clearer.

 if (x > 20) x = 20; if (x < 1) x = 1; 
+4
source

You cannot take max and min variables. However, it is easy to simply insert the variables into the array and find the max and min of the array (with slightly different syntax):

 var value1 = 5; var value2 = 25; var value3 = -3; var arr = []; arr.push(value1); arr.push(value2); arr.push(value3); var maxValue = Math.max.apply(null, arr); var minValue = Math.min.apply(null, arr); alert(maxValue);// ==25 alert(minValue);// ==-3 

or equivalent

 var value1 = 5; var value2 = 25; var value3 = -3; var maxValue = Math.max.apply(null, [value1, value2, value3]); var minValue = Math.min.apply(null, [value1, value2, value3]); alert(maxValue);// ==25 alert(minValue);// ==-3 
+1
source

Source: https://habr.com/ru/post/900841/


All Articles