Javascript 生成随机数的方法
2016-12-22 13:54
302 查看
使用Math.random()函数生成m到n间的随机数字
一.随机生成m(小)-n(大)的数,包含m(小)但不包含n(大)。 下面用小、大表示两数方法一: num=parseInt(Math.random()*(大-小)+小,10);
方法二(m=0的时候): num=parseInt(Math.random()*大,10); 常用于生成数组元素下标,即小=0,把大换成数组长度,也可以用 num=parseInt(Math.random()*大);
function withMwithoutN(m,n) { return parseInt(Math.random()*(n-m)+m,10); }
二.随机生成m(小)-n(大)的数,不包含m但包含n
num=Math.floor(Math.random()*(大-小)+小)+1;
function withoutMwithN(m,n) { return Math.floor(Math.random()*(n-m)+m)+1; }
三.随机生成m(小)-n(大)的数,不包含m和n
num=Math.round(Math.random()*(大-小-2)+小+1) 或者 Math.ceil(Math.random()*(大-小-2)+小);
function withoutMwithoutN(m,n){ return Math.round(Math.random()*(n-m-2)+m+1); }
四.随机生成m(小)-n(大)的数,包含m和n
num=Math.round(Math.random()*(大-小)+小); 或者 Math.ceil(Math.random()*(大-小)+小);
function withMwithN(m,n){ return Math.round(Math.random()*(n-m)+m); }
案例:随机生成50个1到33的数,包含1和33:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> for(var i=0;i<50;i++){ var num=withMwithN(1,33); document.write(num+", "); } </script> </head> <body> </body> </html>
相关文章推荐
- javascript 随机数生成方法
- JavaScript中用于生成随机数的Math.random()方法
- javascript 随机数生成方法
- javascript生成随机数的方法
- JavaScript随机数生成方法
- javascript生成随机数方法汇总
- JavaScript随机数生成方法
- JavaScript中用于生成随机数的Math.random()方法
- JavaScript简单生成 N~M 之间随机数的方法
- JavaScript生成指定范围随机数和随机序列的方法
- javascript 随机数生成方法
- JavaScript中Math.random()方法生成随机数的通用函数
- javascript生成随机数方法汇总
- javascript生成随机数的方法
- sencha(javascript) 中 生成随机数的方法:
- C#中生成随机数的方法和语句
- 生成随机数的三种方法
- Javascript 生成指定范围数值随机数
- JavaScript 动态生成方法的例子
- C/C++程序中生成随机数的方法