生成随机数在很多场景都会用到,所以掌握随机数的生成也是个基本技能
生成随机数常用的几个方法:
1.Math.random(); 生成0-1间的一个随机数(包括0,不包括1)
2.Math.floor(num); 取num的整数部分,向下取整数部分,返回小于等于num的最大整数。
3.Math.round(num); 对num进行四舍五入后的整数。
Math:数学对象,提供对数据的数学计算。
Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。
Math.ceil(n); 返回大于等于n的最小整数。
Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小
随机数的四舍五入常用方法
parseInt()、Math.floor()和Math.ceil()都可以起到四舍五入的作用
var randomNum=Math.random()*10
console.log(randomNum);
console.log(parseInt(randomNum));
console.log(Math.floor(randomNum));
console.log(Math.ceil(randomNum));
**输出的结果**
5.269107830394992
5
5
6
Math.ceil(n) 返回大于n的最小整数
实例:
随机生成1个字符串
function randomString(len) {
len = len || 32;
var ALLCHAR = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var maxPos = ALLCHAR.length;
var pwd = '';
for (i = 0; i < len; i++) {
pwd += ALLCHAR.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
}
console.log(randomString(10));
charAt() 方法可返回指定位置的字符
ALLCHAR.charAt(Math.floor(Math.random() * maxPos)) 解读
Math.random() * maxPos // 生成一个 0-1的数 * maxPos
Math.floor方法 获取1个整数 作为 charAt() 下标 去获取字符串
ALLCHAR=‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’ 中的一个字符