JavaScript随机函数生成的几种情况

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机数函数</title>
</head>
<body>
    <script>
        // 一、随机数函数 random  随机返回0~1之间的小数,包含0,但娶不到1
        console.log(Math.random())

            // 1.如何随机生成0~10的随机小数呢?
            // 公式     :console.log(Math.random() * (10 + 1))  可以取到10 但娶不到11
            console.log(Math.random() * (10 + 1))
            // 2、怎么取整呢?
            console.log(Math.floor(Math.random() * 11))     //直接写在取整方法中当做实参处理后返回的就是整数


                // 代码使用演示     (重点)
                    let arr = ['pink','green','blue']

                    // 随机,并且取整,使用floor方法里面传入随机函数实参,记住取到的最高数一定要加上1
                    let random = Math.floor(Math.random() * arr.length)         //arr.length = 3 操作数组刚好
                    //打印数组随机元素
                    console.log(arr[random])    

            //2.如何生成5~10之间的随机数呢?
            // 公式:Math.floor(Math.random() * (5 + 1) + 5)
            console.log(Math.floor(Math.random() * (5 + 1) + 5))    


            // 3.如何生成   N ~ M  之间的随机数呢 (能取到N  也能取到 M)
            // 公式: Math.floor(Math.random() * (M - N + 1)) + N

                // 代码使用演示     (重点)
                function getRandom(N,M) {
                    return Math.floor(Math.random() * (M - N + 1)) + N
                }
               let x = getRandom(4,8)
                console.log(x)

    </script>
</body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

脱发使我稳重

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值