Math对象-随机数
生成0-1的随机数,包含0,不包含1,结果是浮点数
1- 使用Math对象的random()方法实现
// 控制台输出0-1 随机数,包含 0 不包含 1
console.log(Math.random());
生成0-10的随机整数,包含0,不包含10
1- 使用Math对象的random()方法获取0到1的随机浮点数,包含0,不包含1
2- 将上一步得到的随机浮点数乘以10,得到0-10的随机浮点数,包含0,不包含10
3- 使用Math对象的floor()方法,向下取整,转化为整数
// 控制台输出0-10 的随机整数,包含 0 不包含 10
console.log(Math.floor(Math.random() * 10));
生成5-10的随机整数,包含5,包含10
1- 使用Math对象的random()方法获取0到1的随机浮点数,包含0,不包含1
2- 将上一步得到的随机浮点数乘以6,得到0-6的随机浮点数,包含0,不包含6
3- 在上一步的基础上加上5,得到5-11的浮点数,包含5,不包含11
4- 使用Math对象的floor()方法,向下取整,转化为整数
// 控制台输出5-10 的随机整数,包含 5,包含 10
console.log(Math.floor(Math.random() * 6 + 5));
封装函数,获取min-max的随机整数,包含min,包含max
1- 定义函数,将min,max作为参数传入
2- 使用Math对象的random()方法获取0到1的随机浮点数,包含0,不包含1
3- 将上一步得到的随机浮点数乘以(max-min+1),得到0-(max-min+1)的随机浮点数,包含0,不包含(max-min+1)
4- 在上一步的基础上加上min,得到min-(max+1)的浮点数,包含min,不包含(max+1)
5- 使用Math对象的floor()方法,向下取整,转化为整数
// min max 的随机整数,包含min,包含max
function myRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min)
}
console.log(myRandom(0, 20));