数学函数
Math.random()
随机天生0到1的小数,包含0,不包含1
<script> console.log(Math.random()); // 0.731681187341011 </script>
Math.ceil()
返回大于参数值的最小整数(天花板值),碰到小数向上取整
<script> console.log(Math.ceil(0.0)); // 0 console.log(Math.ceil(-0.0)); // -0 console.log(0 === -0); // true console.log(Math.ceil(2.3)); // 3 console.log(Math.ceil(-1.5)); // -1 </script>
Math.floor()
返回小于参数值的最大整数(地板值),碰到小数向下取整
<script> console.log(Math.floor(0.0)); // 0 console.log(Math.floor(-0.0)); // -0 console.log(0 === -0); // true console.log(Math.floor(2.3)); // 2 console.log(Math.floor(-1.5)); // -2 </script>
Math.round()
四舍五入返回整数
<script> console.log(Math.round(0.49)); // 0 console.log(Math.round(-0.49)); // -0 </script>
Math.max()
返回最大值
<script> let arr = [0.2, 0.32, 12]; console.log(Math.max(arr)); // NaN console.log(Math.max(0.49, 0.231, 932)); // 932 console.log(Math.max(0,-0)); // 0 </script>
Math.min()
返回最小值
<script> let arr = [0.2, 0.32, 12]; console.log(Math.min(arr)); // NaN console.log(Math.min(0.49, 0.231, 932)); // 0.231 console.log(Math.min(0,-0)); // -0 </script>
案例一
恣意局限的随机整数天生函数
<script> // 恣意局限的随机整数天生函数 function getIntRadom(min, max){ let x = Math.random() * (max - min + 1) + min; // [0,1)*5 + 2 -> [0,5) + 2 -> [2,7) return Math.floor(x); // [2,7) -> [2,6] } console.log(getIntRadom(2,6)); </script>
案例二
返回数值的整数部份
<script> // 返回数值的整数部份 function getInt(x){ x = Number(x); return x < 0 ? Math.ceil(x) : Math.floor(x); } console.log(getInt(7.78)); // 7 </script>
案例三
返回数值的整数部份
<script> function random_vlidateCode(x){ let str1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // str1 += "abcdefghijklmnopqrst"; str1 += str1.toLowerCase(); str1 += "0123456789"; let str = ""; for(let i = 0; i < x; i++){ let vlidateCode = Math.floor(Math.random() * str1.length); str += str1.substring(vlidateCode, vlidateCode + 1); } return str; } console.log(random_vlidateCode(4)); // 天生四位随机数 </script>