【JS- 工具类】-随机数

随机数函数

https://www.bilibili.com/video/BV1W54y1J7Ed?p=26

简码 Math.floor(Math.random()*(max-min+1))+min

源码

// 取到min到max(不含)之间的随机数
function getRandom(min,max){
    // 因为用Math.floor()向下取整,所以((max - min) + 1)
    let initNum = Math.random() * ((max - min) + 1);
    let finNum = Math.floor(initNum + min);
    // console.log(finNum);
    return finNum;
}

思路

  • 获取 x ~ y 之间的随机整数!!!
  • 则先取 0 ~ 两数差 之间的随机数,然后 + 小一点得数字
  1. Math.random() 获取一个 0 ~ 0.999… 的随机小数
  2. 将这个数乘于

⭐拓展

注意 Math.round() Math.ceil() Math.floor() 的三种取整值得方法使用!!!!!

会导致取得的数值 0 - 10 概率不同

eg

1. 使用 Math.round()时,每个值取到概率不一样

  • 取0 - 10 随机数

  • // for(i=0;i<100;i++){
    let num = Math.random() * 10;
    let finNum = Math.round(num);
    console.log(finNum);
    // }
    
    
    // num = 0 ~ 0.4999时 ,finNum 取 0
    // num = 0.5 ~ 1.499时,finNum 取 1
    // 以此类推
    // num = 8.5 ~ 9.499时,finNum 取 9
    // num = 9.5 ~ 9.999时,finNum 取 10
    
    // 从而 取0 与 10 的情况将比 取1-9的情况概率要小!!!!!
    

2. 使用 Math.ceil()时,需保持 - 0.99 ~ 0才能取 0不好操作

3. 使用 Math.floor()时,需在10 ~ 10.999才能取10 可行 !!!!!!且每个值概率相同!!

(仅需 在运算时最大值+1 即可—(因为只取0-0.999)即便加1 也无法取最大值+1的整数)

取0 - 10 随机数

for(i=0;i<100;i++){
// 注意乘以 11 ,
// 0.9*11 = 9.9,Math.floor(9.9) = 9!
// 0.91*11 = 10.01,Math.floor(10.01) = 10!
let num = Math.random() * 11;
let finNum = Math.floor(num);
console.log(finNum);
}

拓展

JS 实际例子工具 https://c.runoob.com/examples/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值