js中常用的Math方法總結(jié)
1.min()和max()方法
Math.min()用于確定一組數(shù)值中的最小值。Math.max()用于確定一組數(shù)值中的最大值。
alert(Math.min(2,4,3,6,3,8,0,1,3)); //最小值 alert(Math.max(4,7,8,3,1,9,6,0,3,2)); //最大值
2.舍入方法
Math.ceil()執(zhí)行向上舍入,即它總是將數(shù)值向上舍入為最接近的整數(shù);
Math.floor()執(zhí)行向下舍入,即它總是將數(shù)值向下舍入為最接近的整數(shù);
Math.round()執(zhí)行標準舍入,即它總是將數(shù)值四舍五入為最接近的整數(shù);
例如:
alert(Math.ceil(25.9)); //26 alert(Math.ceil(25.5)); //26 alert(Math.ceil(25.1)); //26 alert(Math.floor(25.9)); //25 alert(Math.floor(25.5)); //25 alert(Math.floor(25.1)); //25 alert(Math.round(25.9)); //26 alert(Math.round(25.5)); //26 alert(Math.round(25.1)); //25
3.random()方法
Math.random()方法返回介于0到1之間一個隨機數(shù),不包括0和1。如果想大于這個范圍的話,可以套用一下公式:
值 = Math.floor(Math.random() * 總數(shù) + 第一個值)
例如:
alert(Math.floor(Math.random() * 10 + 1)); //隨機產(chǎn)生1-10之間的任意數(shù)
for (var i = 0; i<10;i ++) { document.write(Math.floor(Math.random() * 10 + 5)); //5-14之間的任意數(shù) document.write('<br />'); }
為了更加方便的傳遞想要范圍,可以寫成函數(shù):
function selectFrom(lower, upper) { var sum = upper - lower + 1; //總數(shù)-第一個數(shù)+1 return Math.floor(Math.random() * sum + lower); } for (var i=0 ;i<10;i++) { document.write(selectFrom(5,10)); //直接傳遞范圍即可 document.write('<br />'); }
4.其它方法
如下表格:
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
方 法 |
說 明 |
Math.abs(num) |
返回num的絕對值 |
Math.exp(num) |
返回Math.E的num次冪 |
Math.log(num) |
返回num的自然對數(shù) |
Math.pow(num,power) |
返回num的power次冪 |
Math.sqrt(num) |
返回num的平方根 |
Math.acos(x) |
返回x的反余弦值 |
Math.asin(x) |
返回x的反正弦值 |
Math.atan(x) |
返回x的反正切值 |
Math.atan2(y,x) |
返回y/x的反正切值 |
Math.cos(x) |
返回x的余弦值 |
Math.sin(x) |
返回x的正弦值 |
Math.tan(x) |
返回x的正切值 |
- 輕松掌握JavaScript中的Math object數(shù)學對象
- Javascript Math ceil()、floor()、round()三個函數(shù)的區(qū)別
- 使用js Math.random()函數(shù)生成n到m間的隨機數(shù)字
- JavaScript Math.ceil 方法(對數(shù)值向上取整)
- JavaScript Math.floor方法(對數(shù)值向下取整)
- js中Math之random,round,ceil,floor的用法總結(jié)
- 介紹JavaScript中Math.abs()方法的使用
- JavaScript中使用Math.PI圓周率屬性的方法
- js Math 對象的方法
- JavaScript中使用指數(shù)方法Math.exp()的簡介
- JavaScript使用math.js進行精確計算操作示例
- js Math數(shù)學簡單使用操作示例
相關(guān)文章
網(wǎng)頁開發(fā)中的容易忽略的問題 javascript HTML中的table
最近在搞在線電子表格這個東西,下面的是使用中的一些知識技巧。2009-04-04JavaScript 獲取任一float型小數(shù)點后兩位的小數(shù)
這篇文章主要介紹了JavaScript如何獲取小數(shù)任一小數(shù)點后的位數(shù)的小數(shù),需要的朋友可以參考下2014-06-06