声明:本博客的知识点摘录自《JavaScript高级程序设计(第三版)》第五章,如有冒犯,请联系删除
Math对象包含一些属性和方法。
1、属性
2、min()方法和max()方法
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 值。然后,可以将任何数组作为第二个参数。
3、ceil() 、floor() 和 round()方法
- 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.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25
4. random() 方法
Math.random() 方法返回大于等于 0 小于 1 的一个随机数。 套用下面的公式,就可以利用 Math.random()从某个整数范围内随机选择一个值。
值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)
如果想要选择一个介于 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)的一个数值
5. 其他方法
如有错误,请联系作者。