当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js中常用的Math方法总结

js中常用的Math方法总结

2019年03月30日  | 移动技术网IT编程  | 我要评论
1.min()和max()方法 math.min()用于确定一组数值中的最小值。math.max()用于确定一组数值中的最大值。 alert(math.min(

1.min()和max()方法

math.min()用于确定一组数值中的最小值。math.max()用于确定一组数值中的最大值。

alert(math.min(2,4,3,6,3,8,0,1,3));              //最小值
alert(math.max(4,7,8,3,1,9,6,0,3,2));         //最大值

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之间一个随机数,不包括0和1。如果想大于这个范围的话,可以套用一下公式:

值 = math.floor(math.random() * 总数 + 第一个值)

例如:

alert(math.floor(math.random() * 10 + 1));        //随机产生1-10之间的任意数

for (var i = 0; i<10;i ++) {
    document.write(math.floor(math.random() * 10 + 5));       //5-14之间的任意数
    document.write('<br />');
}

为了更加方便的传递想要范围,可以写成函数:

function selectfrom(lower, upper) {
    var sum = upper - lower + 1;                      //总数-第一个数+1
    return math.floor(math.random() * sum + lower);
}
for (var i=0 ;i<10;i++) {
    document.write(selectfrom(5,10));                 //直接传递范围即可
    document.write('<br />');
}

4.其它方法

如下表格:

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

  法

  明

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的正切值

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网