Math中的常用方法
數(shù)學(xué)函數(shù): 雖然它叫函數(shù),但是它是對(duì)象數(shù)據(jù)類型的
typeof Math -> object
Math對(duì)象中給我們提供了很多常用的操作數(shù)字的方法
console.dir(Math) 查看所有方法
- Math.abs(): 取絕對(duì)值
Math.abs(12) // -> 12
Math.abs(-12) // -> 12
- Math.ceil(): 向上取整
Math.ceil(12) // -> 12
Math.ceil(12.1) // -> 13
Math.ceil(12.9) // -> 13
Math.ceil(-12.1) // -> -12
Math.ceil(-12.9) // -> -12
- Math.floor(): 向下取整
Math.floor(12) // -> 12
Math.floor(12.1) // -> 12
Math.floor(12.9) // -> 12
Math.floor(-12.1) // -> -13
Math.floor(-12.9) // -> -13
- Math.round(): 四舍五入
Math.round(12.3) // -> 12
Math.round(12.5) // -> 13
Math.round(-12.3) // -> -12
Math.round(-12.5) // -> -12
Math.round(-12.51) // -> -13
- Math.random(): 獲取[0-1)之間的隨機(jī)小數(shù)
for(var i=0;i<100;i++){
console.log(Math.random()) // 隨機(jī)輸出100個(gè)0-1之間的小數(shù)
}
// -> 獲取[0,10]之間的隨機(jī)整數(shù)
Math.round(Math.random() * 10)
// -> 獲取[3,15]之間的隨機(jī)整數(shù)
Math.round(Math.random()*12+3)
// -> 獲取[n,m]之間的隨機(jī)整數(shù)
Math.round(Math.random()*(m-n) + n)
- Math.max(): 獲取一組值中的最大值
Math.max(12,2,34,1,4,6) // -> 34
- Math.min(): 獲取一組值中的最小值
Math.min(12,2,34,1,4,6) // -> 1
- Math.PI: 獲取圓周率(π)
Math.PI // -> 3.141592653589793
- Math.pow(): 獲取一個(gè)值的多少次冪
Math.pow(10,3) // -> 1000
- Math.sqrt(): 開平方
Math.sqrt(100)