且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

(from) Javascript 生成指定范围数值随机数

更新时间:2022-09-20 19:41:14

查手册后才知道, 介绍的信息少得可怜呐, 没有介绍生成 m-n 范围的随机数..., 就只是给你一个 Math.random() 了事.

不过经过俺的小小努力之后, 终于让俺摸着门道喽, 问题也就理所当然滴解决掉. 

然后就写了个公式, 这样应该可以消失掉这个用法了, 公式:

1. 从1开始 至 任意值

linenum 
parseInt(Math.random()*上限+1); 

2. 从任意值开始 至 任意值

linenum 
parseInt(Math.random()*(上限-下限+1)+下限); 

上面的公式使用了 parseInt(), 因此要加1; 如果使用 Math.ceil() 则不需要加1, 俺习惯于这样写...

目录:
1. 演示1 (直接进行生成随机数操作)
2. 演示2 (写成函数进行生成随机数操作)


1. 演示1 (直接进行生成随机数操作)
linenum 

  1. <script type="text/javascript"> 
  2. //<![CDATA[ 
  3.     window.onload=function(){ 
  4.         var n=na=nb=nc=''; 
  5.             n=parseInt(Math.random()*10+1); 
  6.             na=parseInt(Math.random()*(20-11+1) + 11); 
  7.             nb=parseInt(Math.random()*100+1); 
  8.             nc=parseInt(Math.random()*(100-51+1) + 51); 
  9.              
  10.         var o=document.getElementsByTagName('input'); 
  11.             o[0].value=n; 
  12.             o[1].value=na; 
  13.             o[2].value=nb; 
  14.             o[3].value=nc; 
  15.     } // shawl.qiu script 
  16. //]]> 
  17. </script> 
  18. 1-10: <input type="text" /><br /> 
  19. 11-20: <input type="text" /><br /> 
  20. 1-100: <input type="text" /><br /> 
  21. 51-100: <input type="text" /><br /> 



2. 演示2 (写成函数进行生成随机数操作)

linenum 

    1. <script type="text/javascript"> 
    2. //<![CDATA[ 
    3.     window.onload=function(){ 
    4.         var o=document.getElementsByTagName('input'); 
    5.             o[0].value=fRandomBy(10); 
    6.             o[1].value=fRandomBy(11, 20); 
    7.             o[2].value=fRandomBy(1, 100); 
    8.             o[3].value=fRandomBy(51, 100); 
    9.     } 
    10. function fRandomBy(under, over){ 
    11.         switch(arguments.length){ 
    12.             case 1: return parseInt(Math.random()*under+1); 
    13.             case 2: return parseInt(Math.random()*(over-under+1) + under);  
    14.             default: return 0; 
    15.         } 
    16.     }  // shawl.qiu script 
    17. //]]> 
    18. </script> 
    19. 1-10: <input type="text" /><br /> 
    20. 11-20: <input type="text" /><br /> 
    21. 1-100: <input type="text" /><br /> 
    22. 51-100: <input type="text" /><br /> 



    23. 本文转自94cool博客园博客,原文链接:http://www.cnblogs.com/94cool/p/3214726.html,如需转载请自行联系原作者