Partial Extension of Math Object in ES6
- 2021-07-22 08:49:57
- OfStack
1. Math. trunc ()
This method is used to take out the decimal part of 1 decimal and return the integer part. Look at the example:
Math.trunc(1.234); //1
Math.trunc(-2.34141); //-2
Math.trunc(3.9); //3
// For non-numeric values, Math.trunc Will be used internally Number Convert it to a numeric value
Math.trunc("12.87656"); //12
// For null values and values that cannot truncate integers, return NaN
Math.trunc("a"); //NaN
Math.trunc(); //NaN
Math.trunc(NaN); //NaN
2. Math. sign ()
This method is used to judge whether a number is positive, negative or 0. There are 5 return values. Look at the following example:
Math.sign(23.235); //1
Math.sign(25); //1
Math.sign(0); //0
Math.sign(0.0); //0
Math.sign(-0.0); //-0
Math.sign(-0); //-0
Math.sign(-2); //-1
Math.sign(-2.983958); //-1
Math.sign('a'); //NaN
Math.sign(); //NaN
Math.sign(NaN); //NaN
Returns 1 when the parameter is positive;
Returns 0 when the parameter is 0;
Returns-0 when the parameter is-0;
Returns-1 when the parameter is negative;
NaN is returned when the parameter is another value.
3. Math. cbrt ()
This method is used to calculate the cube root of a number, which is equivalent to Math. pow (n, 1/3) method.
Math.cbrt(8); //2
Math.cbrt(-64); //-4
// For non-numeric values, this method also uses the Number Method to convert it into a numerical value, and then calculate it
Math.cbrt("125"); //5
Math.cbrt("a"); //NaN
4. Math. hypot ()
This method is used to calculate the square root of the sum of squares of all parameters.
Math.hypot(3,4); //5
Math.hypot(1,2,3); //3.741657386773941
Math.hypot(-5); //5
Math.hypot(); //0
Math.hypot(NaN); //NaN
Math.hypot("a"); //NaN
Math.hypot(3,'4'); //5
Math.hypot(3,'a'); //NaN
The above methods can greatly simplify the code, which is very convenient.