Math:數(shù)學(xué)函數(shù),并不是一個函數(shù),而是一個對象 ,一下列舉了一些較常用的Math方法及用法
-
Math.abs([number value]):獲取絕對值
如果傳的不是數(shù)字,則會自動通過Number()轉(zhuǎn)換再取絕對值console.log(Math.abs('-1'))//1 console.log(Math.abd('1px'))//NAN console.log(Math.abs(true))//1 -
Math.ceil/floor([number value]):向上、向下取整
向上取整一定是比原數(shù)大,(向下則相反)//Math.ceil() console.log(Math.ceil(12))//12 console.log(Math.ceil(12.1))//13 console.log(Math.ceil(12.7))//13 console.log(Math.ceil(-12.1))//-12 console.log(Math.ceil(-12.6))//-12 //Math.floor() console.log(Math.floor(-12.1))//-13 console.log(Math.floor(-12.6))//-13 -
Math.round():四舍五入
無大小之分,在正數(shù)中.5進(jìn),負(fù)數(shù)中.5舍console.log(Math.round(12.4))//12 console.log(Math.round(12.5))//13 console.log(Math.round(-12.5))//12 console.log(Math.round(-12.6))//13 -
Math.max/min([val1],[val2],…):取一堆數(shù)中的最大值最小值 -
Math.sqrt/pow()
sprt:開平方
pow(數(shù)值的幾次冪)console.log(Math.pow(2,10))//1024 -
Math.random():隨機(jī)數(shù)
擴(kuò)展:獲取[n~m之間的隨機(jī)數(shù)]
獲取1-10之間的隨機(jī)數(shù)Math.round(Math.random()*(m-n)+n)
獲取0-1之間的隨機(jī)數(shù)Math.round(Math.random()*9+1)Math.round(Math.random()) -
Math.PI:
Math.PI非函數(shù),是一個數(shù)值
更多詳情:Math方法