JavaScript[21] -- 数学函数
数学函数
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>
相关推荐
chensen 2020-11-14
lwnylslwnyls 2020-11-06
ATenhong 2020-10-15
yanzhelee 2020-10-13
佛系程序员J 2020-10-10
guojin0 2020-10-08
佛系程序员J 2020-10-08
bluewelkin 2020-09-16
wwzaqw 2020-09-04
zhongdaowendao 2020-09-02
favouriter 2020-08-18
奎因amp华洛 2020-08-15
一青年 2020-08-13
千锋 2020-08-10
nangongyanya 2020-08-09
dongxurr 2020-08-08
明天你好 2020-08-03
kyelu 2020-08-03
Ashes 2020-08-03