随机函数(随机取数)

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随机的不固定
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值