Math 对象
Math对象用于保存数学公式和信息,本文将介绍Math对象提供的常用计算属性和方法。
1. Math 对象的属性
Math 对象包含的属性大都是数学计算中可能会用到的一些特殊值。下表列出了这些属性。
2. min()和 max()方法
min()和 max()方法用于确定一组数值中的最小值和最大值,这两个方法都可以接收任意多个数值参数
示例:
var max = Math.max(1, 2, 3, 4,5);
alert(max); //5
var min = Math.min(1, 2, 3, 4,5);
alert(min); //1
这两个方法经常用于避免多余的循环和在 if 语句中确定一组数的最大值。
3. 舍入方法
绍将小数值舍入为整数的方法
3.1 Math.ceil()
执行向上舍入,即它总是将数值向上舍入为最接近的整数
示例:
alert(Math.ceil(1.9)); //2
alert(Math.ceil(1.5)); //2
alert(Math.ceil(1.1)); //2
3.2Math.floor()
执行向下舍入,即它总是将数值向下舍入为最接近的整数
示例:
alert(Math.floor(1.9)); //1
alert(Math.floor(1.5)); //1
alert(Math.floor(1.1)); //1
3.3Math.round()
执行标准舍入,即它总是将数值四舍五入为最接近的整数
示例:
alert(Math.round(1.9)); //2
alert(Math.round(1.5)); //2
alert(Math.round(1.1)); //1
4. random()方法
Math.random()方法返回大于等于 0 小于 1 的一个随机数
该方法常搭配 Math.floor()方法,用于获得某一区间的随机数 , 写法:
值 = Math.floor(Math.random() 可能值的总数 + 第一个可能的值
举例:
随机生成一个1-10之间的数值:
var num = Math.floor(Math.random( ) * 10 + 1);
5. 其他方法
Math 对象中还包含其他一些与完成各种简单或复杂计算有关的方法