JS - Math.random() 随机数

5,310 阅读2分钟

前言

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情

当时在学习项目的时候,遇到一个功能需要随机返回多条不重复的数据,当时也是拿了就用,下次再需要时已经忘记如何使用了;虽然接触使用的场景很少,但也有必要单独拿出来讲一讲

定义

js中的生成随机数操作是基于 Math 方法下的 random() 方法

Math.random() : 随机获取范围内的一个数 ( 精确到小数点后14位 )

基础写法

  • 随机生成一个 0 ~ 1 之间的数
 // 语法: Math.random()

image-20220526085038117

生成指定范围内的随机数

  • 生成 小于 m 的随机数(含小数)
 // 语法: Math.random() * m 
 Math.random() * 60 

image-20220526085125942

  • 生成 小于m 的整数

可以使用 parseInt 去除小数点的形式将生成的随机数转换为整数

 // 语法: Math.random() * m 
 parseInt(Math.random()* 60)

image-20220526085145973

  • 生成向下取整的随机整数

使用Math方法下的floor属性进行舍弃小数向下取整, 当然你也可以使用 Math.ceil 向上取整

 // 语法: Math.random() * m 
 Math.floor(Math.random()* 60)

image-20220526085608144

生成两个数之间的随机数

  • 表示生成 n~m+n 之间的随机数
 // 语法: Math.random() * m + n  
 // 范围:n ~ m+n
 Math.random() * 10 + 8  // 8 ~ 18 

image-20220526090426508

  • 生成 -n~m+n 之间的随机数
 // 语法: Math.random() * m - n 
 // 范围:-n ~ m+n
 Math.random() * 10 - 8  // -8 ~ 2

image-20220526090730373

  • 生成 -m~0 之间的随机数
 // 语法: Math.random() * m - m 
 // 范围:-m - 0
 Math.random() * 10 - 10  // -10 - 0

image-20220526091239692

  • 生成 n~m 之间的随机整数(包括n与m)
 // 语法: Math.floor(Math.random() * (m - n)) + n
 // 范围:n ~ m
 Math.floor(Math.random() * (8 - 100)) + 100  // 8~100

image-20220526091642107

常用场景

看完语法,接下来讲一个我项目中用到的场景 - 热榜

将每次随机获取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 就介绍到这了