简介?
个人简介:某双非普通大学在校大学生一枚??
个人主页:-Baymax- ?♂️
博客内容:WEB前端(html、css、JavaScript、Vue、AJAX、ES6…) ?
支持大白:点赞?、收藏⭐、关注?
文章目录
前言
随机数 的生成在很多时候是很重要的。比如 抽奖功能 的实现就要利用随机数,下面是随机数 生成 和 使用 的 常见用法,希望对你有所帮助。
一、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(), 我们可以在此基础上,进行向下取整、四舍五入等操作,达到我们预期的目标。
二、写在最后的话✍
这篇文章能被你看到,是我很大的 荣幸!?
如果这篇文章对你有些帮助,不妨 点赞?、关注? 支持一下。
你的支持是我继续精心创作的 强大动力!??
不积跬步无以至千里? ,不积小流无以成江海?。
道阻且长,一起加油,与君共勉!?
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/210783.html原文链接:https://javaforall.net
