Math对象
一、相关概念
ECMAScript还为保存数学公式和信息提供了一个公共位置,即Math
对象 Math
对象中还提供了辅助完成这些计算的属性和方法
二、Math对象的属性
Math
对象包含的属性大都是数学计算中可能会用到的一些特殊值
属性 说明 Math.E
自然对数的底数,即常量e的值 Math.LN10
10的自然对数 Math.LN2
2的自然对数 Math.LOG2E
以2为底e的对数 Math.LOG10E
以10为底e的对数 Math.PI
∏的值 Math.SQRT1_2
1/2的平方根(即2的平方根的倒数) Math.SQRT2
2的平方根
三、min()和max()方法
1.min()方法
min()
方法用于确定一组数值中的最小值都可以接受任意多个数值参数
var min=Math.min(3,54,32,16);
alert(min);//3
2.max()方法
min()
方法用于确定一组数值中的最大值都可以接受任意多个数值参数
var max=Math.max(3,54,32,16);
alert(max);//54
3.applly()
要找到数组中的最大值或最小值,可以使用apply()方法 这个方法的关键是把Math
对象作为apply()
的第一个参数,从而正确的使之this
值。然后,可以将任何数组作为第二个参数
var values=[1,2,3,4,5,6,7,8];
var max=Math.max.apply(Math,values);
四、舍入方法
1.Math.ceil()
执行向上舍入,即它总是将数值向上舍入为最接近的整数
alert(Math.ceil(25.9));//26
alert(Math.ceil(25.5));//26
alert(Math.ceil(25.1));//26
2.Math.floor()
执行向下舍入,即它总是将数值向下舍入为最接近的整数
alert(Math.floor(25.9));//25
alert(Math.floor(25.5));//25
alert(Math.floor(25.1));//25
3.Math.round()
执行标准舍入,即它总是将数值四舍五入为最接近的整数
alert(Math.round(25.9));//26
alert(Math.round(25.5));//26
alert(Math.round(25.1));//25
五、random()方法
1.相关概念
Math.random()
返回方法返回大于等于0小于1的一个随机数值=Math.floor(Math.random()*可能值的总数+第一个可能的值)
var num=Math.floor(Math.random()*10+1);//1到10
var num=Math.floor(Math.random]()*9+2);//2到10
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","green","blue","yellow","black","purple","brown"];
var color=colors[selectFrom(0,colors.length-1)];
alert(color);//可能是数组中包含的任何一个字符串
六、其他方法
方法 说明 Math.abs(num)
返回num
的绝对值 Math.exp(num)
返回Math.E
的num
次幂 Math.log(num)
返回num
的自然对数 Math.pow(num,power)
返回num
的power
次幂 Math.sqrt(num)
返回num
的平方根 Math.acos(x)
返回x
的反余弦值 Math.asin(x)
返回x
的反正弦值 Math.atan(x)
返回x
的反正切值 Math.atan2(y,x)
返回y/x
的反正切值 Math.cos(x)
返回x
的余弦值 Math.sin(x)
返回x
的正弦值 Math.tan(x)
返回x
的正切值
源于整理《JavaScript高级程序设计》