您的位置:首页 > Web前端 > JavaScript

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  生成 随机数