Math随机数

这篇博客介绍了JavaScript中生成随机数的方法,包括如何生成指定范围内的整数。作者通过示例展示了如何使用Math.random()函数,并提供了一个自定义函数getRandom()来在两个数之间生成随机整数。此外,还展示了如何利用这些随机数进行随机点名的应用,例如从一个数组中随机选取名字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script>
        // 1.random()返回一个随机的小数  [0,1)
        console.log(Math.random());

        // 推导过程
        // 获取0-10之间的数 [0,10)
        // [0,1)*10 = [0,10)
        console.log(Math.floor(Math.random()*10));
        // 获取1-10之间的数 [0,10]
        // [0,1)* 10 +1 = [1,10]
        console.log(Math.floor(Math.random()*10 +1));
        // 获取20-50之间的数 [20,50]
        // [0,1)* (50-20+1) + 20= [20,50]
        // 0  +  20   20
        // 31 +  20   50
        console.log(Math.floor(Math.random()*(50-20+1)+20));
        


        // 2.得到两个数之间的随机整数 [min,max]
        function getRandom(min,max){
            return Math.floor(Math.random()*(max - min + 1)) + min;
        }
        console.log(getRandom(1,10));

        // 3.随机点名
        var arr = ['虞书欣','赵晓棠','安琦'];
        console.log(arr[getRandom(0,arr.length - 1)]);
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值