Javascript 生成指定范围数值随机数

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

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

  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

  <script type="text/javascript">

  //<![CDATA[

  window.onload=function(){

  var n=na=nb=nc='';

  n=parseInt(Math.random()*10+1);

  na=parseInt(Math.random()*(20-11+1) + 11);

  nb=parseInt(Math.random()*100+1);

  nc=parseInt(Math.random()*(100-51+1) + 51);

  var o=document.getElementsByTagName('input');

  o[0].value=n;

  o[1].value=na;

  o[2].value=nb;

  o[3].value=nc;

  } // shawl.qiu script

  //]]>

  </script>

  1-10: <input type="text" /><br />

  11-20: <input type="text" /><br />

  1-100: <input type="text" /><br />

  51-100: <input type="text" /><br />

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

  linenum

  <script type="text/javascript">

  //<![CDATA[

  window.onload=function(){

  var o=document.getElementsByTagName('input');

  o[0].value=fRandomBy(10);

  o[1].value=fRandomBy(11, 20);

  o[2].value=fRandomBy(1, 100);

  o[3].value=fRandomBy(51, 100);

  }

  function fRandomBy(under, over){

  switch(arguments.length){

  case 1: return parseInt(Math.random()*under+1);

  case 2: return parseInt(Math.random()*(over-under+1) + under);

  default: return 0;

  }

  } // shawl.qiu script

  //]]>

  </script>

  1-10: <input type="text" /><br />

  11-20: <input type="text" /><br />

  1-100: <input type="text" /><br />

  51-100: <input type="text" /><br />