JavaScript随机函数生成随机数介绍并使用

Math.random( )是随机函数:随机取0~1之间的任意数; 1、四舍五入函数 如果是一位整数,那么就要用到四舍五入函数:Math.round( ); 例如: alert(Math.round(3.4));//3alert(Math.round(3...

Math.random( )是随机函数:随机取0~1之间的任意数;


1、四舍五入函数

如果是一位整数,那么就要用到四舍五入函数:Math.round( );

例如:

alert(Math.round(3.4));//3
alert(Math.round(3.5));//4


2、随机0和1

alert(Math.round(Math.random()));//随机取0或1


3、随机0-10之间数字

alert(Math.round(Math.random()*10));//随机取0到10之间任意数


4、随机5-10之间数字

alert(Math.round(Math.random()*5+5));//随机取5到10之间任意数


5、随机10-20之间数字

alert(Math.round(Math.random()*10+10));//随机取10到20之间任意数


6、随机20-100之间数字

alert(Math.round(Math.random()*80+20));//随机取20到100之间任意数


5、随机0-100之间数字

alert(Math.round(Math.random()*100));//随机取0到100之间任意数


7、随机X-Y之间的数字

alert(Math.round(Math.random()*(Y-X)+X));//随机取X到Y之间任意数


8、随机0-X之间的数字

alert(Math.round(Math.random()*X));//随机取0到X之间任意数


9、随机1-X之间的数字

alert(Math.ceil(Math.random()*X));//随机取1到X之间任意数

Math.ceil( )向上取整;

// Math.random()是随机函数
var arr = [1,2,3,4,5];
arr.sort(function(a,b){
    return Math.random();
});
alert(arr);//2,4,3,1,5随机的不固定

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
admin
admin

651 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章