js随机数random()方法

js随机数random()方法

 

  var  num=Math.random();//生成一个[0-1)的随机数即包括0,不包括1这个是值域取值。

  第一、通常我们会生成一个0-9的随机整数,比如用来for里面的循环次数;

   var a=parseInt(Math.random()*10,10);  //取值范围 [0,9]

   var b=Math.floor(Math.random()*10); //取值范围 [0,9]

   var c=Math.ceil(Math.random()*9);//取值范围 [0,9]

   // parseIn(string,radix); radix如果省略该参数或其值为 0,则数字将以10为基础来解析。[2,36]参数值为2 或者大于 36,则 parseInt() 将返回 NaN

         由上可见Math.ceil()的取值跟Math.floor()和parseInt()存在一个差异为1的问题。

 

  第二、生成1到任意随机数x(max)的问题:

   var  d=parseInt(Math.random()*x,10)+1;

   var  e=Math.floor(Math.random()*x)+1;

   var  f=Math.ceil(Math.random()*x);

 

 第三、任意随机数x(min)到y(max)的取值范围:

  var   g=parseInt(Math.random()*(y-x+1)+x,10);

  var   h=Math.floor(Math.random()*(y-x+1)+x);

  var   k=Math.ceil(Math.random()*(y-x)+x);

posted @ 2016-10-09 16:09  海贼还在贼贼笑  阅读(590)  评论(0编辑  收藏  举报