1.min()和max()方法
Math.min()用于确定一组数值中的最小值。Math.max()用于确定一组数值中的最大值。
rush:js;">
alert(Math.min(2,4,3,6,8,1,3)); //最小值
alert(Math.max(4,7,9,2)); //最大值
2.舍入方法
Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;
Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;
Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数;
例如:
rush:plain;">
alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
3.random()方法
Math.random()方法返回介于0到1之间一个随机数,不包括0和1。如果想大于这个范围的话,可以套用一下公式:
值 = Math.floor(Math.random() * 总数 + 第一个值)
例如:
alert(Math.floor(Math.random() * 10 + 1)); //随机产生1-10之间的任意数
rush:js;">
for (var i = 0; i<10;i ++) {
document.write(Math.floor(Math.random() * 10 + 5)); //5-14之间的任意数
document.write('
'); }
'); }
为了更加方便的传递想要范围,可以写成函数:
rush:js;">
function selectFrom(lower,upper) {
var sum = upper - lower + 1; //总数-第一个数+1
return Math.floor(Math.random() * sum + lower);
}
for (var i=0 ;i<10;i++) {
document.write(selectFrom(5,10)); //直接传递范围即可
document.write('
'); }
'); }
4.其它方法
如下表格:
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程之家!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。