js随机数生成

基础知识

Math.abs()    //取绝对值 不四舍五入
Math.floor();  //向下取整。
Math.ceil();  //向上取整。
Math.round();  //四舍五入取整。
Math.random();  //返回 0(含)和 1(不含)之间的随机数 [0,1)

parseInt();  //第一个参数对以数字开头的字符串或数字都能向下取整,第二个参数默认为10进制

parseInt与Math.floor区别

Math.floor只能对一个数向下取整,不能解析字符串

Math.floor(1.5) // 1
Math.floor(-2.1) // -3
Math.floor("3")  // 3
Math.floor('Hello') // NaN
Math.floor('16岁') // NaN

parseInt(string, radix)可将任意数字开头字符串转换为相应整数,后一个参数表进制,可取值2/8/10/16,默认是十进制

parseInt(1.5) // 1
parseInt(1.2) // 1
parseInt(-2.1) // -2
parseInt('3') // 3
parseInt('hello')  // NaN
parseInot('16岁') // 16

1.生成[0,max)的随机数:

parseInt(Math.random() * max);
Math.floor(Math.random() * max);  

2.生成[0,max]的随机数:

// max - 最大值
parseInt(Math.random() * (max + 1));
Math.floor(Math.random() * (max + 1));

因为Math.random()生成[0,1)的数,所以1是取不到的。那么如果想最大值取到1,就需要最大值加1,但是加完1后最大值多了点,所以还需要parseInt或Math.floor向下取整。

3.生成[1,max]的随机数:

// max - 最大值
parseInt(Math.random() * max) + 1;
Math.floor(Math.random() * max) + 1;

4.生成[min,max]的随机数:

// max - 最大值
// min - 最小值
parseInt(Math.random() * (max - min + 1) + min);
Math.floor(Math.random() * (max - min + 1) + min);

运用

随机生成一个字符串

function hash () {
  let s = ''
  const strs = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 
    'h', 'i', 'j', 'k', 'l', 'm', 'n', 
    'o', 'p', 'q', 'r', 's', 't', 'u', 
    'v', 'w', 'x', 'y', 'z', '0', '1', 
    '2', '3', '4', '5', '6', '7', '8',
    '9',
  ]
  for(let i = 0; i < 10; i++) {
    s += strs[Math.floor(Math.random() * strs.length)]
  }
  return s
}

hash() 

简化版

//36代表36进制
const str = Math.random().toString(36).substr(2,10)
console.log(str)    
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值