这篇“JavaScript中随机数方法Math.random()怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JavaScript中随机数方法Math.random()怎么使用”文章吧。
js中的生成随机数操作是基于 Math
方法下的 random()
方法
Math.random() : 随机获取范围内的一个数 ( 精确到小数点后14位 )
随机生成一个 0 ~ 1 之间的数:
// 语法: Math.random()
生成 小于 m 的随机数(含小数):
// 语法: Math.random() * m
Math.random() * 60
生成 小于m 的整数:
可以使用 parseInt
去除小数点的形式将生成的随机数转换为整数
// 语法: Math.random() * m
parseInt(Math.random()* 60)
生成向下取整的随机整数:
使用Math
方法下的floor
属性进行舍弃小数向下取整, 当然你也可以使用 Math.ceil
向上取整
// 语法: Math.random() * m
Math.floor(Math.random()* 60)
表示生成 n~m+n 之间的随机数:
// 语法: Math.random() * m + n
// 范围:n ~ m+n
Math.random() * 10 + 8 // 8 ~ 18
生成 -n~m+n 之间的随机数:
// 语法: Math.random() * m - n
// 范围:-n ~ m+n
Math.random() * 10 - 8 // -8 ~ 2
生成 -m~0 之间的随机数:
// 语法: Math.random() * m - m
// 范围:-m - 0
Math.random() * 10 - 10 // -10 - 0
生成 n~m 之间的随机整数(包括n与m):
// 语法: Math.floor(Math.random() * (m - n)) + n
// 范围:n ~ m
Math.floor(Math.random() * (8 - 100)) + 100 // 8~100
看完语法,接下来讲一个我项目中用到的场景 - 热榜,将每次随机获取3条不重复的热门数据
function random_pick(list, target) {
/**
* @param {number[]} list - 数据
* @param {number} target - 获取的条数
*/
// 1. 保存热榜
let hot = [];
// 2. 保存热榜的索引
for (let index = 0; index < list.length; index++) {
// 3. 如果热榜采集完,则直接返回
if (hot.length >= target) return hots(hot);
// 4. 每次随机取出一个数
let r = Math.floor(Math.random() * list.length);
// 5. 如果随机数不在热榜里,则加入热榜
if (hot.indexOf(r) == -1) {
hot.push(r);
}
}
// 热榜过滤函数
function hots(params) {
return params.map(item => { return list[item] });
}
}
let r = random_pick([22, 33, 44, 55, 66, 77, 88], 3)
以上就是关于“JavaScript中随机数方法Math.random()怎么使用”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。