zoukankan      html  css  js  c++  java
  • (from) Javascript 生成指定范围数值随机数

    from:http://blog.csdn.net/ilibaba/article/details/3741786

    查手册后才知道, 介绍的信息少得可怜呐, 没有介绍生成 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 /> 
  • 相关阅读:
    JS-记住用户名【cookie封装引申】
    JS-cookie封装
    JS-比较函数中嵌套函数,可以排序【对象数组】
    JS-随机div颜色
    JS-过滤敏感词【RegExp】
    JS-提取字符串—>>普通方法VS正则表达式
    CSS- ie6,ie7,ie8 兼容性写法,CSS hack写法
    JS-【同页面多次调用】轮播特效封装-json传多个参数
    JS-【同页面多次调用】tab选项卡封装
    Redis主从同步
  • 原文地址:https://www.cnblogs.com/94cool/p/3214726.html
Copyright © 2011-2022 走看看