Math對象是JavaScript的內置對象穿肄,提供一系列數(shù)學常數(shù)和數(shù)學方法年局。Math對象只提供了靜態(tài)的屬性和方法,所以使用時不用實例化
屬性
Math對象提供以下一些只讀的數(shù)學常數(shù)咸产。
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
方法
round
round方法用于四舍五入
Math.round(0.1) // 0
Math.round(0.5) // 1
它對于負值的運算結果與正值略有不同矢否,主要體現(xiàn)在對.5的處理
Math.round(-1.1) // -1
Math.round(-1.5) // -1
abs,max脑溢,min
abs方法返回參數(shù)值的絕對值
Math.abs(1) // 1
Math.abs(-1) // 1
max方法返回最大的參數(shù)僵朗,min方法返回最小的參數(shù)
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
floor,ceil
floor方法返回小于參數(shù)值的最大整數(shù)
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
ceil方法返回大于參數(shù)值的最小整數(shù)
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
pow屑彻,sqrt
pow方法返回以第一個參數(shù)為底數(shù)验庙、第二個參數(shù)為冪的指數(shù)值
Math.pow(2, 2) // 4
Math.pow(2, 3) // 8
sqrt方法返回參數(shù)值的平方根。如果參數(shù)是一個負值酱酬,則返回NaN
Math.sqrt(4) // 2
Math.sqrt(-4) // NaN
log壶谒,exp
log方法返回以e為底的自然對數(shù)值
Math.log(Math.E) // 1
Math.log(10) // 2.302585092994046
求以10為底的對數(shù),可以除以Math.LN10膳沽;求以2為底的對數(shù)汗菜,可以除以Math.LN2让禀。
Math.log(100)/Math.LN10 // 2
Math.log(8)/Math.LN2 // 3
exp方法返回常數(shù)e的參數(shù)次方
Math.exp(1) // 2.718281828459045
Math.exp(3) // 20.085536923187668
random
該方法返回0到1之間的一個偽隨機數(shù),可能等于0陨界,但是一定小于1
Math.random() // 0.7151307314634323
// 返回給定范圍內的隨機數(shù)
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
// 返回給定范圍內的隨機整數(shù)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
三角函數(shù)
sin方法返回參數(shù)的正弦巡揍,cos方法返回參數(shù)的余弦,tan方法返回參數(shù)的正切菌瘪。
Math.sin(0) // 0
Math.cos(0) // 1
Math.tan(0) // 0
asin方法返回參數(shù)的反正弦腮敌,acos方法返回參數(shù)的反余弦,atan方法返回參數(shù)的反正切俏扩。這三個方法的返回值都是弧度值糜工。
Math.asin(1) // 1.5707963267948966
Math.acos(1) // 0
Math.atan(1) // 0.7853981633974483