js生成随机数

发布时间:2025-12-09 11:54:13 浏览次数:1

一生成随机数方法

需要使用Math 对象,Math 对象中生成随机数的函数是Math.random(),所以想要生成随机数并打出的方式为

    console.log(Math.random())

Math 对象中常用的函数除了Math.random()外,常用的函数还有Math.round()和Math.ceil()和 Math.floor分别是四舍五入、向上取整、向下取整的意思

二生成随机数简单案例

1.生成50-100随机数方法

方法一:先使用复杂一些的方式,因为Math.random()生成的随机数在0-1之间,所以让这个数*100,得到大小0-100间数字,然后使用if函数判定,如果这个数小于50则增加50,并输出,如果大于50直接输出

a=Math.random()*100    if(a<50){        a=a+50    }    console.log(a)//50-100

使用三元运算符简化函数

console.log(a>50?a:a=a+50)    console.log(a)//50-100

方法二:先生成一个0-50的数,再增加50得到50-100的数

 b=(Math.random()*100)/2    console.log(b)//0-50    c=b+50    console.log(c)//50-100

方法三:方法三准确来说是对方法二的简化,思路一样

  console.log(Math.random()*50+50)


2.生成80-100随机数

     console.log(Math.random()*20+80)

3.生从min-max随机数

  console.log(Math.random()*(max-min)+min)
js随机数
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477