JS內(nèi)置對象和Math對象知識點(diǎn)詳解
Math對象
<script> // Math數(shù)學(xué)對象 不是一個(gè)構(gòu)造函數(shù) ,所以我們不需要new 來調(diào)用 而是直接使用里面的屬性和方法即可 console.log(Math.PI); // 一個(gè)屬性 圓周率 console.log(Math.max(1, 99, 3)); // 99 console.log(Math.max(-1, -10)); // -1 console.log(Math.max(1, 99, ’pink老師’)); // NaN console.log(Math.max()); // -Infinity </script>
自己封裝對象
<script> // 利用對象封裝自己的數(shù)學(xué)對象 里面有 PI 最大值和最小值 var myMath = { PI: 3.141592653, max: function() {var max = arguments[0];for (var i = 1; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; }}return max; }, min: function() {var min = arguments[0];for (var i = 1; i < arguments.length; i++) { if (arguments[i] < min) { min = arguments[i]; }}return min; } } console.log(myMath.PI); console.log(myMath.max(1, 5, 9)); console.log(myMath.min(1, 5, 9)); </script>
一些常用的方法
<script> // 1.絕對值方法 console.log(Math.abs(1)); // 1 console.log(Math.abs(-1)); // 1 console.log(Math.abs(’-1’)); // 隱式轉(zhuǎn)換 會把字符串型 -1 轉(zhuǎn)換為數(shù)字型 console.log(Math.abs(’pink’)); // NaN // 2.三個(gè)取整方法 // (1) Math.floor() 地板 向下取整 往最小了取值 console.log(Math.floor(1.1)); // 1 console.log(Math.floor(1.9)); // 1 // (2) Math.ceil() ceil 天花板 向上取整 往最大了取值 console.log(Math.ceil(1.1)); // 2 console.log(Math.ceil(1.9)); // 2 // (3) Math.round() 四舍五入 其他數(shù)字都是四舍五入,但是 .5 特殊 它往大了取 console.log(Math.round(1.1)); // 1 console.log(Math.round(1.5)); // 2 console.log(Math.round(1.9)); // 2 console.log(Math.round(-1.1)); // -1 console.log(Math.round(-1.5)); // 這個(gè)結(jié)果是 -1 </script>
<script> // 1.Math對象隨機(jī)數(shù)方法 random() 返回一個(gè)隨機(jī)的小數(shù) 0 =< x < 1 // 2. 這個(gè)方法里面不跟參數(shù) // 3. 代碼驗(yàn)證 console.log(Math.random()); // 4. 我們想要得到兩個(gè)數(shù)之間的隨機(jī)整數(shù) 并且 包含這2個(gè)整數(shù) // Math.floor(Math.random() * (max - min + 1)) + min; function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } console.log(getRandom(1, 10)); // 5. 隨機(jī)點(diǎn)名 var arr = [’張三’, ’張三豐’, ’張三瘋子’, ’李四’, ’李思思’, ’pink老師’]; // console.log(arr[0]); console.log(arr[getRandom(0, arr.length - 1)]); </script>
到此這篇關(guān)于JS內(nèi)置對象和Math對象知識點(diǎn)詳解的文章就介紹到這了,更多相關(guān)JS內(nèi)置對象和Math對象內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)2. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案3. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera4. HTML DOM setInterval和clearInterval方法案例詳解5. 使用css實(shí)現(xiàn)全兼容tooltip提示框6. css代碼優(yōu)化的12個(gè)技巧7. css進(jìn)階學(xué)習(xí) 選擇符8. 告別AJAX實(shí)現(xiàn)無刷新提交表單9. HTML <!DOCTYPE> 標(biāo)簽10. CSS hack用法案例詳解
