js获取随机数

js 获取随机数方法如下:

1.Math.random()表示 结果为0-1间的一个随机数(包括0,不包括1) ;

  返回指定范围的随机数(m-n之间)的公式

  Math.random()*(n-m)+m;

  Math.random()*10+5; //返回5-15之间的随机数

2.Math.ceil(n) 返回大于等于n的整数

  用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。

3、Math.round(n); 返回n四舍五入后整数的值。  

  用Math.round(Math.random());可均衡获取0到1的随机整数。
  用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10

  的几率少一半。

4、Math.floor(n); 返回小于等于n的最大整数。

  用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。

5、基于时间,亦可以产生随机数

1 var now=new Date();
2 var number = now.getSeconds(); //这将产生一个基于目前时间的0到59的整数。
3 
4 var now=new Date();
5 var number = now.getSeconds()%43; //这将产生一个基于目前时间的0到42的整数。

参考来源:http://www.studyofnet.com/news/181.html

例子:js获取随机颜色

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6 </head>
 7 <style type="text/css">
 8     #box{width: 100px;height: 100px;margin: 20px auto;background-color: #c66;}
 9 </style>
10 <body>
11     <div id="box" onclick="getColor();">box1</div>
12     <script type="text/javascript">
13     var x,y,z;
14     var oBox=document.getElementById('box');
15     function getColor(box){
16         x=Math.round(Math.random()*255);
17         y=Math.round(Math.random()*255);
18         z=Math.round(Math.random()*255);
19         oBox.style.backgroundColor='rgb('+x+','+y+','+z+')';
20     }
21     </script>
22 </body>
23 </html>

坚持下去,相信自己。

转载于:https://www.cnblogs.com/MissBean/p/4137245.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值