码迷,mamicode.com
首页 > Web开发 > 详细

js获取随机数

时间:2014-12-02 14:43:52      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   java   on   

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>

坚持下去,相信自己。

js获取随机数

标签:style   blog   http   io   ar   color   sp   java   on   

原文地址:http://www.cnblogs.com/MissBean/p/4137245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!