JavaScript —— 生成随机数
简介👇
前言
随机数 的生成在很多时候是很重要的。比如 抽奖功能 的实现就要利用随机数,下面是随机数 生成 和 使用 的 常见用法,希望对你有所帮助。
一、Math对象方法(随机数)
1. random():返回 0 ~ 1 之间的随机数,包含 0 不包含 1。
let ran = Math.random()
console.log(ran) //随机生成一个0~1的数 但不包含1
2. floor():返回小于等于 x 的最大整数。
let ran = Math.floor(8.3)
console.log(ran) //8
3. ceil():返回大于等于 x 的最接近整数。
let ran = Math.ceil(8.3)
console.log(ran) //9
4. round():返回一个数字舍入的最近的整数(四舍五入)。
let ran = Math.round(8.3)
console.log(ran) //8
let ran = Math.round(8.5)
console.log(ran) //9
常见实例
1. 取介于 1 到 10 之间的随机数。
let ran = Math.floor((Math.random()*10) + 1)
console.log(ran) //返回1~10之间的随机数(包括10)
2. 返回 min(包含)~ max(不包含)之间的数字。
function getRnd(min, max){
return Math.floor(Math.random() * (max - min)) + min
}
3. 返回 min(包含)~ max(包含)之间的数字。
function getRnd(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min
}
总结
随机数的生成离不开 Math.random(), 我们可以在此基础上,进行向下取整、四舍五入等操作,达到我们预期的目标。
二、写在最后的话✍
不积跬步无以至千里🌕 ,不积小流无以成江海🌊。 道阻且长,一起加油,与君共勉!😉
