javascript 实现随机数解析[转]

Math对象中的方法
       Math.random() 该方法返回一个0到1之间的随机数,不包括0和1。
  要实现获得一个maxNumber到minNumber范围内的随机整数,实现方法如下:
       choNumber=maxNumber-minNumber+1;
       number=Math.floor(Math.random()*choNumber+minNumber)
                   
  例:
      选择一个1到10之间的随机数:
            number=Math.floor(Math.random()*10+1);
      可能出现的值有10个,最小的值为1。
     选择一个2到10之间的随机数:
            number=Math.floor(Math.random()*9+2);
      可能出现的值有9个,最小的值为2。
解释:Math.floor()用来获取一个整数,将小数转换成整数。

通过函数实现从一个数组中随机选择一个值:
  实现selectFrom()函数获得一个iFirstValue到iLastValue之间的随机整数
function selectFrom(iFirstValue,iLastValue)
        {
            var iChoices=iLastValue-iFirstValue+1;
             return Math.floor(Math.random()*iChoices+iFirstValue);
        }

例:
      

   var aColors=["red","green","yellow","black","blue","purple","brown"];
  var sColors=aColors[selectFrom(0,aColors.length-1)]
posted @ 2008-11-28 15:26  aoogur  阅读(346)  评论(0编辑  收藏  举报