js生成随机数

介绍几个函数

  • Math.ceil():向上取整

    console.log(Math.ceil(1.3)); // 2
    console.log(Math.ceil(-1.3)); // -1
    console.log(Math.ceil(0)); // 0
    
  • Math.floor():向下取整

    console.log(Math.floor(1.3)); // 1
    console.log(Math.floor(-1.3)); // -2
    
  • Math.round():四舍五入

    console.log(Math.round(1.4)); // 1
    console.log(Math.round(1.5)); // 2
    console.log(Math.round(-1.4)); // -1
    console.log(Math.round(-1.5)); // -1
    
  • Math.random():[0,1) 之间的随机数(包括 0 但不包括 1),其产生的随机数位数,我见过的有 17 位到 20 位的,包括第一位的 0 和小数点

生成 [0, max] 的随机整数

parseInt(Math.random() * (max + 1),10);

Math.floor(Math.random() * (max + 1));

//基本均衡获取 0 到 max 的随机整数,但获取最小值 0 和最大值 max 的几率要少一半
//因为结果在 0~0.4 时,最终结果为 0;而结果 0.5~1.4 时,最终结果为 1
Math.round(Math.random() * max); 

生成 [1, max] 的随机整数

parseInt(Math.random() * max,10) + 1;

Math.floor(Math.random() * max) + 1;

Math.ceil(Math.random() * max); //有可能取到 0,但概率极小

生成 [min, max] 的随机整数

parseInt(Math.random() * (max - min + 1) + min,10);

Math.floor(Math.random() * (max - min + 1) + min);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值