常用屬性
- PI π值一部分
Math.PI
//3.141592653589793
常用方法
**注:接收參數(shù)為number類型,如使用非number類型則方法會(huì)嘗試使用Number(number)方法去轉(zhuǎn)換為Number類型,而不是使用 parseFloat(number) **
- abs(number) 獲取參數(shù)的絕對(duì)值
Math.abs(10)//10
Math.abs(-10)//10
Math.abs("10")//10
Math.abs("10abc")//NaN
window.parseFloat("10abc")//10
Number("10abc")//NaN
- ceil(number)向上取整
Math.ceil(10.0001)//11
Math.ceil("10.99abc")//NaN
- floor(number) 向下取整
Math.floor(10.2) //10
Math.floor(10.99)//10
Math.floor("10.99")//10 字符串參數(shù)
Math.floor("10.99abc")//NaN
- max(numberX,numberY,...) 獲取輸入?yún)?shù)中最大的一個(gè)
Math.max(10,200,400)//400
Math.max("1077",200,400)//1077 注意返回值是Number類型,而不是String類型
Math.max([1,2,3],[4,5,6]) //NaN
- min(numberX,numberY,...)獲取輸入?yún)?shù)中最小的一個(gè)
Math.min(10,200,400)//10
Math.min(1077,"200",400)//200 注意返回值是Number類型,而不是String類型
Math.min([1,2,3],[4,5,6]) //NaN
- pow (numberX,numberY) 獲取參數(shù)x的y次方,參數(shù)二沒有默認(rèn)值
Math.pow(8,2)//64
Math.pow("8",2)//64
Math.pow("8","2")//64
Math.pow("8")//NaN 參數(shù)二沒有默認(rèn)值
- random() 返回0-1的隨機(jī)數(shù)
Math.random()//0.636911032255739
- round(number) 四舍五入保留整數(shù),保留幾位小數(shù)是Number的方法.toFixed
Math.round(10.499)//10
Math.round(10.500)//11
123.43323.toFixed() //"123",當(dāng)參數(shù)為空時(shí)默認(rèn)保留到整數(shù),注意返回的是String而不是Number
123.43323.toFixed(2)//"123.43"
123.toFixed(2)//Uncaught SyntaxError: Unexpected token ILLEGAL 這里報(bào)錯(cuò)了是因?yàn)橄到y(tǒng)把123后面的點(diǎn)當(dāng)成了是小數(shù)點(diǎn)而非調(diào)用方法點(diǎn)
(123).toFixed(2)//"123.00" ,當(dāng)小數(shù)點(diǎn)后不足兩位時(shí),該方法會(huì)自動(dòng)不足,這也是為什么返回值為字符串而非數(shù)值的原因
以上方法是我認(rèn)為Math中最常用的屬性和方法,其他方法未整理,具體可見:w3cshool-JavaScript Math 對(duì)象 .