Math对象

Math对象

一、相关概念

  1. ECMAScript还为保存数学公式和信息提供了一个公共位置,即Math对象
  2. Math对象中还提供了辅助完成这些计算的属性和方法

二、Math对象的属性

  1. Math对象包含的属性大都是数学计算中可能会用到的一些特殊值
属性说明
Math.E自然对数的底数,即常量e的值
Math.LN1010的自然对数
Math.LN22的自然对数
Math.LOG2E以2为底e的对数
Math.LOG10E以10为底e的对数
Math.PI∏的值
Math.SQRT1_21/2的平方根(即2的平方根的倒数)
Math.SQRT22的平方根

三、min()和max()方法

1.min()方法
  1. min()方法用于确定一组数值中的最小值
  2. 都可以接受任意多个数值参数
var min=Math.min(3,54,32,16);
alert(min);//3
2.max()方法
  1. min()方法用于确定一组数值中的最大值
  2. 都可以接受任意多个数值参数
var max=Math.max(3,54,32,16);
alert(max);//54
3.applly()
  1. 要找到数组中的最大值或最小值,可以使用apply()方法
  2. 这个方法的关键是把Math对象作为apply()的第一个参数,从而正确的使之this值。然后,可以将任何数组作为第二个参数
var values=[1,2,3,4,5,6,7,8];
var max=Math.max.apply(Math,values);

四、舍入方法

1.Math.ceil()
  1. 执行向上舍入,即它总是将数值向上舍入为最接近的整数
alert(Math.ceil(25.9));//26
alert(Math.ceil(25.5));//26
alert(Math.ceil(25.1));//26
2.Math.floor()
  1. 执行向下舍入,即它总是将数值向下舍入为最接近的整数
alert(Math.floor(25.9));//25
alert(Math.floor(25.5));//25
alert(Math.floor(25.1));//25
3.Math.round()
  1. 执行标准舍入,即它总是将数值四舍五入为最接近的整数
alert(Math.round(25.9));//26
alert(Math.round(25.5));//26
alert(Math.round(25.1));//25

五、random()方法

1.相关概念
  1. Math.random()返回方法返回大于等于0小于1的一个随机数
  2. 值=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.Enum次幂
Math.log(num)返回num的自然对数
Math.pow(num,power)返回numpower次幂
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高级程序设计》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值