SarahHShen 2019-06-28
随机生成0到1的小数,包括0,不包括1
<script> console.log(Math.random()); // 0.731681187341011 </script>
返回大于参数值的最小整数(天花板值),遇到小数向上取整
<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>
返回小于参数值的最大整数(地板值),遇到小数向下取整
<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>
四舍五入返回整数
<script> console.log(Math.round(0.49)); // 0 console.log(Math.round(-0.49)); // -0 </script>
返回最大值
<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>
返回最小值
<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>