JS数据类型之Math对象
2015-09-12 21:24
711 查看
Math对象
1.min()和max()方法这两个方法都可以接收任意多个数值参数,例子如下:
var max=Math.max(3,54,32,16); alert(max); //54 var min=Math.min(3,54,32,16); alert(min); //3
要找到数组中的最大或最小值,可以像下面这样使用apply()方法。
var values=[1,2,3,4,5,6,7,8]; var max=Math.max.apply(Math,values);
这个技巧的关键是把Math对象作为apply()的第一个参数,从而正确地设置this值。然后可以将任何数组作为第二个参数。
2.舍入方法
Math.ceil()、Math.floor()、Math.round()
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的一个随机数。
值=Math.floor(Math.random()*可能值的总数+第一个可能的值)
如果想选择一个1到10之间的数值,代码如下:
var num=Math.floor(Math.random()*10+1);
如果想选择一个2到10之间的数值,代码如下:
var num=Math.floor(Math.random()*9+2);
多数情况下,可以通过一个函数来计算可能值的总数和第一个可能的值,例如:
function selectFrom(lowerValue,upperValue){ var choices=upperValue-lowerValue+1; return Math.floor(Math.random()*choices+lowerValue); } var num=selectFrom(2,10); alert(num); //介于2和10之间(包括2和10)的一个值
利用这个函数,可以方便地从数组中随机取出一项,例如:
var colors=["red","blue","yellow","black","purple"]; var color=colors[selectFrom(0,colors.length-1)]; alert(color); //可能是数组中包含的任何一个字符串
相关文章推荐
- Servlet和JSP的区别
- QQ空间留言的JS
- javaScript
- "use strict"; ----Javascript 严格模式详解
- js制作带有遮罩弹出层实现登录小窗口
- js ie非ie浏览器的几种判断方法小结
- [LeetCode][JavaScript]Search for a Range
- javascript HTML DOM listener
- JS于,子类调用父类的函数
- 使用JavaScript检测浏览器
- javascript高级程序设计---Event对象三
- js实现网页贪吃蛇
- javascript高级程序设计---Event对象二
- JavaScript 的 坑
- JS数据类型之String类型
- javascript高级程序设计---Event对象
- [LeetCode][JavaScript]First Bad Version
- JavaScript : the good parts(语言精髓读书笔记)
- js实现找零张数最小问题
- JSP页面细节