星空网 > 软件开发 > Java

JS产生随机数的几个用法!

转自  http://www.cnblogs.com/banbu/archive/2012/07/25/2607880.html

JS产生随机数的几个用法!
 1 <script> 2function GetRandomNum(Min,Max) 3 {  4   var Range = Max - Min;  5   var Rand = Math.random();  6   return(Min + Math.round(Rand * Range));  7 }  8var num = GetRandomNum(1,10);  9alert(num);  10 </script>11 12 var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];13 14 function generateMixed(n) {15   var res = "";16   for(var i = 0; i < n ; i ++) {17     var id = Math.ceil(Math.random()*35);18     res += chars[id];19   }20   return res;21 }            
JS产生随机数的几个用法!

 


1.Math.random(); 结果为0-1间的一个随机数(包括0,不包括1) 
2.Math.floor(num); 参数num为一个数值,函数结果为num的整数部分。 
3.Math.round(num); 参数num为一个数值,函数结果为num四舍五入后的整数。

Math:数学对象,提供对数据的数学计算。
Math.random(); 返回0和1间(包括0,不包括1)的一个随机数。

Math.ceil(n); 返回大于等于n的最小整数。
用Math.ceil(Math.random()*10);时,主要获取1到10的随机整数,取0的几率极小。

Math.round(n); 返回n四舍五入后整数的值。
用Math.round(Math.random());可均衡获取0到1的随机整数。
用Math.round(Math.random()*10);时,可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。

Math.floor(n); 返回小于等于n的最大整数。
用Math.floor(Math.random()*10);时,可均衡获取0到9的随机整数。






原标题:JS产生随机数的几个用法!

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

安庆市空运:https://www.goluckyvip.com/tag/102803.html
空运快递有哪些:https://www.goluckyvip.com/tag/102804.html
柳州空运:https://www.goluckyvip.com/tag/102805.html
行李空运:https://www.goluckyvip.com/tag/102806.html
fra空运:https://www.goluckyvip.com/tag/102807.html
国际空运大包:https://www.goluckyvip.com/tag/102809.html
卓欧毕雪酒店推荐:https://www.vstour.cn/a/404237.html
响沙湾门票套票价格大介绍(省钱攻略必备):https://www.vstour.cn/a/404238.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流