- The Math object allows you to perform mathematical tasks.
- The Math object includes several mathematical methods.
One common use of the Math object is to create a random number:
Math.random(); // returns a random number 點後.16位
Math has no constructor. No methods have to create a Math object first.
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:
Math.min(0, 150, 30, 20, -8); // returns –8
Math.max(0, 150, 30, 20, -8); // returns 150
Math.round() 四捨五入取整數
Math.round() rounds a number to the nearest integer:
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.ceil() 無條件UP取大整數
Math.ceil() rounds a number up to the nearest integer:
Math.ceil(4.4); // returns 5
Math.ceil(-4.9); // returns -4
Math.floor() 無條件down取小整數
Math.floor() rounds a number down to the nearest integer:
Math.floor(4.7); // returns 4
Math.floor(-4.7); // returns -5
Math.floor() and Math.random() can be used together to return a random number between 0 and 10:利用這個方法來得到一個0到10的整數
Math.floor(Math.random() * 11);
// returns a random number between 0 and 10
Math Constants 八個常數值
JavaScript provides 8 mathematical constants that can be accessed with the Math object:
Math.E; // returns Euler's number
Math.PI // returns PI 圓周率
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Math Object Methods(真正的數學函數!)
Method | Description |
abs(x) | Returns the absolute value of x //絶對值 |
acos(x) | Returns the arccosine of x, in radians |
asin(x) | Returns the arcsine of x, in radians |
atan(x) | Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians |
atan2(y,x) | Returns the arctangent of the quotient of its arguments |
ceil(x) | Returns x, rounded upwards to the nearest integer |
cos(x) | Returns the cosine of x (x is in radians) |
exp(x) | Returns the value of Ex |
floor(x) | Returns x, rounded downwards to the nearest integer |
log(x) | Returns the natural logarithm (base E) of x |
max(x,y,z,...,n) | Returns the number with the highest value |
min(x,y,z,...,n) | Returns the number with the lowest value |
pow(x,y) | Returns the value of x to the power of y //次方 |
random() | Returns a random number between 0 and 1 |
round(x) | Rounds x to the nearest integer |
sin(x) | Returns the sine of x (x is in radians) |
sqrt(x) | Returns the square root of x //開根號 |
tan(x) | Returns the tangent of an angle |
Complete Math Reference
For a complete reference, go to our complete Math object reference.
The reference contains descriptions and examples of all Math properties and methods.
沒有留言:
張貼留言