javascript內(nèi)置對象Math案例總結(jié)分析
Math概述
Math 對象不是構(gòu)造函數(shù),它具有數(shù)學常數(shù)和函數(shù)的屬性和方法。跟數(shù)學相關(guān)的運算(求絕對值,取整、最大值等)可以使用 Math 中的成員。
Math中常用函數(shù)的用法
Math.PI //圓周率 Math.floor () //向下取整 Math.ceil () //向上取整 Math.round () //四舍五入就近取整 注意﹣3.5 結(jié)果是-3 Math.abs () //絕對值 Math.max ()/Math.min() //求最大值和最小值 Math.random() //返回一個隨機的小數(shù) 0=<x<1(這個方法里面不跟參數(shù))
1.絕對值方法
//1.絕對值方法 console.log(Math.abs(1)); // 1 console.log(Math.abs(-1)); //1 console.log(Math.abs('-5')); //5 會隱式轉(zhuǎn)換,將數(shù)字字符串轉(zhuǎn)換為數(shù)字,然后取絕對值 console.log(Math.abs('aniu')); // NaN
2.三個取整方法
//2.三個取整方法 console.log(Math.floor(1.1)); //1 console.log(Math.floor(1.9)); //1 console.log(Math.floor(-1.1)); //-2 console.log(Math.ceil(1.1)); // 2 console.log(Math.ceil(1.9)); //2 console.log(Math.ceil(-1.9)); //-1 console.log(Math.round(1.5)); //2 四舍五入 .5這個特殊,是往大了取 console.log(Math.round(-1.5)); // -1 往大了取 console.log(Math.round(-1.2)); // -1
3.求最大值/最小值
//3.求最大值/最小值 console.log(Math.max(1,5,78,46)); console.log(Math.min(1,5,78,46));
4.隨機數(shù)
//4.隨機數(shù) console.log(Math.random());
案例
求兩個數(shù)之間的隨機整數(shù)的小算法(重要)
求兩個數(shù)之間的隨機整數(shù) 并且包含這兩個數(shù):
//核心算法 Math.floor(Math.random()*(max-min)) + min;
function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log(getRandom(1,7));
隨機點名
//隨機點名 var arr = ['阿牛','夢夢','小鳴人','winter','小何','WA','賤神','扎哇'] //太多啦,就寫這些舉例啦 console.log(arr); console.log('阿牛愛你們??????'); function getRandom(min,max){ return Math.floor(Math.random()*(max-min)) + min; } console.log('隨機點中了:' + arr[getRandom(0,arr.length - 1)]);
結(jié)語
以上就是javascript內(nèi)置對象Math案例總結(jié)分析的詳細內(nèi)容,更多關(guān)于javascript內(nèi)置對象Math的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Jsonp 關(guān)鍵字詳解及json和jsonp的區(qū)別,ajax和jsonp的區(qū)別
這篇文章主要介紹了Jsonp 關(guān)鍵字詳解及json和jsonp的區(qū)別,ajax和jsonp的區(qū)別 的相關(guān)資料,需要的朋友可以參考下2015-12-12smartupload實現(xiàn)文件上傳時獲取表單數(shù)據(jù)(推薦)
這篇文章主要介紹了smartupload實現(xiàn)文件上傳時獲取表單數(shù)據(jù)的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-12-12JavaScript實現(xiàn)購物車圖片局部放大預覽效果
這篇文章主要為大家詳細介紹了JavaScript如何通過canvas簡單實現(xiàn)購物車圖片放大預覽效果,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2023-03-03基于JavaScript實現(xiàn)網(wǎng)紅太空人表盤的完整代碼
這篇文章主要介紹了基于JavaScript實現(xiàn)網(wǎng)紅太空人表盤的完整代碼,代碼簡單易懂,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03JavaScript高級程序設(shè)計 讀書筆記之八 Function類及閉包
Function類及閉包,學習js的朋友可以參考下2012-02-02