js Math.rander的用法


前言

本文展示了求js随机数的一些常用用法

一、基础随机数求法

获取一个 [0,1) 的随机数

    var random1 = Math.random()
    console.log(random1); //0.15502465163041257

Math.random()方法 得出的是一个大于或者等于0 然后最大可以无限接近于1 不等于1的随机值
所有扩展用法都是基于这个取值范围得到的

二、基础用法扩展

生成 [one, two) 范围内的随机数

    function getRandom1(one, two) {
        if (one < two) {
            return Math.random() * (two - one) + one
        } else {
            return Math.random() * (one - two) + two
        }
    }
    console.log(getRandom1(2, 4), '<'); // 3.021933876110561 '<'
    console.log(getRandom1(4, 2), '>'); // 3.2829077427720192 '>'

生成 (one, two) 范围内的随机数

    function getRandom2(one, two) {
        if (one < two) {
            var data = Math.random() * (two - one) + one
            while (data !== one) {
                return data
            }
            return getRandom2(one, two)
        } else {
            var data = Math.random() * (one - two) + two
            while (data !== one) {
                return data
            }
            return getRandom2(one, two)
        }
    }
    console.log(getRandom2(2, 3), '()'); // 2.684042669080733 '()'

三、再扩展

生成指定位数的随机数
代码如下(示例):

  function random3(n) {
        let Begin = ''
        for (let i = 0; i < n; i++) {
            Begin += Math.floor(Math.random() * 10)
        }
        let result = Number(Begin)
        return result
    }
    console.log(random3(9), 'DIYnumber'); // 735140887 'DIYnumber'

可以结合 Math 其他的一些方法 对得到的随机值进行取整等操作


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值