js生成随机数

108 阅读1分钟

Math对象中常用的方法

Math.abs();//取绝对值,不四舍五入
Math.floor();//向下取整数, 1.2👉1; -1.2👉-2
Math.ceil();//向上取整,1.2👉2,-1.2👉-1
Math.round();//四舍五入,值得注意的是-1.5👉-1,-1.6👉-2
Math.pow(x,y);//返回x的y次方
parseInt();//第一个参数对应数字开头的字符串或者数字都能向下取整,第二个参数默认为10进制

parseInt与Math.floor区别

Math.floor只能对一个数字向下取整,不能解析字符串 parseInt从第一位截取连续的数字字符串,当第一位不是数字的时候,会返回NaN

Math.floor(1.5);//1
parseInt(1.5);//1
Math.floor("123");//123
parseInt('123');//123
Math.floor("Hello");//NaN, 提到NaN,想到了isNaN()方法,这个方法中传入数字字符串也是判定是数字
parseInt("World");//NaN
Math.floor("26岁");//NaN
parseInt("26岁");//26

正片

  1. 生成[1,max]的随机数
parseInt(Math.random()*max)+1;
Math.floor(Math.random()*(max+1));
  1. 生成[min,max]的随机数
parseInt(Math.random()*(max-min+1)+min);
Math.floor(Math.random()*(max-min+1)+min);
  1. 生成n位的随机数
parseInt(Math.random()*(Math.pow(10,n)));
  1. 生成一个随机字符串
function randomX(len){
    let r = "";
    const strs = ['0','1','2','3','4','5','6','7','8','9','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']
    for(let i=len; i>0;i--){
     r += strs[Math.floor(Math.random()*strs.length)]
    }
    return r
}
randomX(10)
//生成一个普通随机数,利用小树转36进制的特点生成最多10位的随机数
Math.random().toString(36).substr(2,10);