?
? ????? PHP ??? ???? ??? ?? ??
屬性
方法
round方法
abs方法,max方法,min方法
floor方法,ceil方法
pow方法,sqrt方法
log方法,exp方法
random方法
三角函數方法
Math對象是JavaScript的內置對象,提供一系列數學常數和數學方法。
該對象不是構造函數,所以不能生成實例,所有的屬性和方法都必須在Math對象上調用。
new Math() // TypeError: object is not a function
上面代碼表示,Math不能當作構造函數用。
Math對象提供以下一些只讀的數學常數。
E:常數e。
LN2:2的自然對數。
LN10:10的自然對數。
LOG2E:以2為底的e的對數。
LOG10E:以10為底的e的對數。
PI:常數Pi。
SQRT1_2:0.5的平方根。
SQRT2:2的平方根。
這些常數的值如下。
Math.E // 2.718281828459045 Math.LN2 // 0.6931471805599453 Math.LN10 // 2.302585092994046 Math.LOG2E // 1.4426950408889634 Math.LOG10E // 0.4342944819032518 Math.PI // 3.141592653589793 Math.SQRT1_2 // 0.7071067811865476 Math.SQRT2 // 1.4142135623730951
Math對象提供以下一些數學方法。
round方法用于四舍五入。
Math.round(0.1) // 0 Math.round(0.5) // 1
它對于負值的運算結果與正值略有不同,主要體現在對.5的處理。
Math.round(-1.1) // -1 Math.round(-1.5) // -1
abs方法返回參數值的絕對值。
Math.abs(1) // 1 Math.abs(-1) // 1
max方法返回最大的參數,min方法返回最小的參數。
Math.max(2, -1, 5) // 5 Math.min(2, -1, 5) // -1
floor方法返回小于參數值的最大整數。
Math.floor(3.2) // 3 Math.floor(-3.2) // -4
ceil方法返回大于參數值的最小整數。
Math.ceil(3.2) // 4 Math.ceil(-3.2) // -3
power方法返回以第一個參數為底數、第二個參數為冪的指數值。
Math.pow(2, 2) // 4 Math.pow(2, 3) // 8
sqrt方法法返回參數值的平方根。如果參數是一個負值,則返回NaN。
Math.sqrt(4) // 2 Math.sqrt(-4) // NaN
log方法返回以e為底的自然對數值。
Math.log(Math.E) // 1 Math.log(10) // 2.302585092994046
求以10為底的對數,可以除以Math.LN10;求以2為底的對數,可以除以Math.LN2。
Math.log(100)/Math.LN10 // 2Math.log(8)/Math.LN2 // 3
exp方法返回常數e的參數次方。
Math.exp(1) // 2.718281828459045 Math.exp(3) // 20.085536923187668
該方法返回0到1之間的一個偽隨機數,可能等于0,但是一定小于1。
Math.random() // 0.7151307314634323 // 返回給定范圍內的隨機數 function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } // 返回給定范圍內的隨機整數 function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
sin方法返回參數的正弦,cos方法返回參數的余弦,tan方法返回參數的正切。
Math.sin(0) // 0 Math.cos(0) // 1 Math.tan(0) // 0
asin方法返回參數的反正弦,acos方法返回參數的反余弦,atan方法返回參數的反正切。這個三個方法的返回值都是弧度值。
Math.asin(1) // 1.5707963267948966 Math.acos(1) // 0 Math.atan(1) // 0.7853981633974483