赞
踩
随机数random()
1、Math对象里面随机数方法,random()返回一个随机的小数 0 <= x < 1;
2、这个方法里面不跟参数;
3、验证代码:
console.log(Math.random())
4、如果得到随机整数,并且包含这2个整数:
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, 100))

5、拓展:随机点名
//封装一个随机数函数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min
}
var arrName = ["小白", "小红", "小蓝", "小妞", "小牛", "小黑", "小明"]
console.log(arrName[getRandom(0, arrName.length - 1)])
6、补充一点
<script> /* 随机数:Math.random() 得到的是一个0-1(包含0但是不包含1)的随机数 0*10-1*10---0-10 不包含10 得到一个0-10的随机整数数 Math.random()*11 在取整 得到一个 10-30的随机整数 0-1 --- 0*31-1*31---0+10-30+10 --10-40 0*21-1*21--0+10-20+10 ----10-30 */ // console.log(parseInt(Math.random() * 11)); // console.log(parseInt(Math.random() * 21 + 10)); // 30 到 80 之间的随机数 *51+30 // console.log(parseInt(Math.random() * 51 + 30)); // 编写一个函数,求任意两个数值之间的随机数,并返回 function randomNum(n, m) { // (0-1)*191--(0-191)+10--10-201 191 = 200-10 + 1 // return parseInt(Math.random() * 191 + 10) // 判断两个参数的大小 var max, min; max = n > m ? n : m; min = n < m ? n : m; // (0-1)*6--(0-6)+10--10--16 6 = 15-10- +1 return parseInt(Math.random() * (max - min + 1) + min); // (0-1)*(-7)-7--0--18--25 } console.log(randomNum(27, 20)); </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。