js随机数
在javascript中用来生成随机熟的方法是Math下的random方法:
random():函数返回从0到1之间的一个浮点数,包括0但是不包括1,
获取 两个数之间的随机整数,不包括不包括最大值
// 得到两个数之间的整数值,不包括最大值 /* minValue: 表示要生成的随机数的起始值,包括该值(有可能大于等于该值) maxValue: 表示要生成随机数的终止,不包括该值(小于等于该值) */ function selectFrom(minValue, maxValue) {
// 通过最大值减去最小值然后加1得到取值的范围可能值的总数 // 例如取2到10之间的整数,10-2 = 8 var choices = maxValue - minValue; // 然后通过随机数乘以刚才的到的值, // 例如:Math.random() * 8,由于得到的是小于1的随机数,所以随机最大值0.99*8得到的数始终小于8 // 然后使用floor方法向下取正得到的数最大值就是7,然后再加上最小值 return Math.floor(Math.random() * choices + minValue); } var num = selectFrom(2, 10); console.log(num);
获取两个数之间的随整数,包括最大值
// 和上边的方法一样只是内部有一点一样 function selectFrom(minValue, maxValue) {
// 在这里求区间的时候加1操作,就可以了 var choices = maxValue - minValue + 1; return Math.floor(Math.random() * choices + minValue); } // 介于 2 和 10 之间(包括 2 和 10)的一个数值 // 10-2=8 var num = selectFrom(2, 10); console.log(num);
随机获取一组数中的数据
var arr = [10, 20, 5, 10, 30, 50, 22, 45, 67, 5, 4, 2, 12]; var a = Math.floor(Math.random() * arr.length + 1)
随机生成某个字符串中的值
var randomS = function(len) {
var chars = '12345qwertyuiopasdfgh67890jklmnbvcxzMNBVCZXASDQWERTYHGFUIOLKJP', maxPos = chars.length, pwd = '', i; len = len || 5; for (i = 0; i < len; i++) {
pwd += chars.charAt(Math.floor(Math.random() * maxPos)); } return pwd; } //随机获取5个字符串 randomS(5);
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/223778.html原文链接:https://javaforall.net
