Math對象是JavaScript的內(nèi)置對象,提供一系列數(shù)學(xué)常數(shù)和數(shù)學(xué)方法。Math對象只提供了靜態(tài)的屬性和方法,所以使用時不用實例化
常用方法
round
round方法用于四舍五入:
Math.round(0.1) // 0
Math.round(0.5) // 1
abs, max, min
abs方法返回參數(shù)值的絕對值
Math.abs(2) // 2
Math.abs(-2) // 2
max方法返回最大的參數(shù),min方法返回最小的參數(shù)
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
floor, ceil
floor方法返回小于參數(shù)值的最大整數(shù)
ceil方法返回大于參數(shù)值的最小整數(shù)
pow, sqrt
pow方法返回以第一個參數(shù)為底數(shù)、第二個參數(shù)為冪的指數(shù)值
Math.pow(2, 2) // 4
Math.pow(2, 3) // 8
sqrt方法返回參數(shù)值的平方根。如果參數(shù)是一個負(fù)值,則返回NaN
random
該方法返回0到1之間的一個偽隨機數(shù),可能等于0,但是一定小于1.