JS内置对象-Math对象

常量

Math对象有8个常量,主要包括对数、派值和平方根

对数

Math.E          自然对数的底数(常量e值),约等于2.718
Math.LN2        2的自然对数,约等于0.693
Math.LN10       10的自然对数,约等于2.303
Math.LOG2E      以2为底e的对数,约等于1.443
Math.LOG10E     以10为底e的对数,约等于0.434

关于数值e,可以参考知乎这篇文章

派值

Math.PI         派值(圆周率),约等于3.14

平方根

Math.SQRT2      2的平方根,约等于1.414
Math.SQRT1_2    1/2的平方根(2的平方根的倒数),约等于0.707

函数

Math对象有18个静态函数,主要包含最值、舍入、随机数、三角函数、乘方和开方。这些函数都涉及到Number()隐式类型转换,若超出范围,将返回NaN。

最值

Math.min()和Math.max()方法用于获取一组数中的最小值和最大值,这两个方法都可以接受任意个数参数。

【Math.min()】返回参数中的最小值。如果没有参数就返回Infinity,如果任意一个参数是NaN或不可转换为数字,则返回NaN。

Math.min(1,2,3) // 1
Math.min() // Infinity
Math.min(1,2,'a') // NaN

【Math.max()】返回参数中的最大值。如果没有参数就返回-Infinity,如果任意一个参数是NaN或不可转换为数字,则返回NaN。

Math.max(1,2,3) // 3
Math.max() // -Infinity
Math.max(1,2,'a') // NaN

扩展: 获取数组中的最大值或最小值。

var arr = [1,2,3,4,5];
Math.min.apply(Math,arr) // 1
Math.max.apply(Math,arr) // 5

舍入

小数的舍入方法有三个:

【Math.ceil()】向上取整,返回大于或等于最近接函数参数的整数。

【Math.floor()】向下取整,返回小于或等于最近接函数参数的整数。

【Math.round()】四舍五入。

Math.ceil(3.14) // 4
Math.ceil(-3.14) // -3

Math.floor(3.14) // 3
Math.floor(-3.14) // -4

Math.round(3.14) // 3
Math.round(-3.14) // -3

随机数

Math.random()方法返回一个大于等于0小于1的随机数。

利用公式从某个整数范围内随机选择一个值

var num = Math.floor(Math.random()*(upperValue - lowerValue + 1) + lowerValue);

获取2-5范围内的一个随机数。

Math.floor(Math.random()*(5 - 2 + 1) + 2);

从数组中随机获取一项

var arr = [2,5,3,6,7];
arr[Math.floor(Math.random()*arr.length)];

随机获取01值

Math.round(Math.random())

绝对值

Math.abs(num)获取任意数值的绝对值

console.log(Math.abs(-1));//1
console.log(Math.abs('-1px'));//NaN

三角函数

和三角函数相关的函数有7个:正弦、余弦、正切、反正弦、反余弦、反正切、y/x的反正切值

【Math.sin(x)】返回x的正弦值,值介于-1到1之间。

【Math.cos(x)】返回x的余弦值,值介于-1到1之间。

【Math.tan(x)】返回x的正切值。

【Math.asin(x)】返回x的反正弦值,返回值介于-π/2到π/2弧度之间(x必须是-1到1之间的数)。

【Math.acos(x)】返回x的反余弦值,返回值介于0到π弧度之间(x必须是-1到1之间的数)。

【Math.atan(x)】返回x的反正切值,返回值介于-π/2到π/2弧度之间。

【Math.atan2(y,x)】返回y/x的反正切值,返回值介于-π到π之间。可以将y看做点的y坐标,x看做点的x坐标,y坐标必须在x坐标前面。

注意: x是一个弧度制度量的角度。如果需要把角度制转化成弧度制,可以把角度制的值乘以0.017(2π/360)

console.log(Math.sin(30 * Math.PI/180));//0.49999999999999994    
console.log(Math.cos(60 * Math.PI/180));//0.5000000000000001
console.log(Math.tan(45 * Math.PI/180));//0.9999999999999999    
console.log(Math.asin(1) * 180/Math.PI);//90
console.log(Math.acos(1) * 180/Math.PI);//0
console.log(Math.atan(1) * 180/Math.PI);//45
console.log(Math.atan2(1,1) * 180/Math.PI);//45

乘方开方

和乘方开方相关的函数有4个:

【Math.exp(num)】返回e的num次幂,即enum

console.log(Math.exp(0));//1
console.log(Math.exp(1));//2.718281828459045

【Math.log(num)】返回num的自然对数,即logenum(num必须大于等于0)。

console.log(Math.log(1));//0
console.log(Math.log(Math.E));//1

【Math.sqrt(num)】返回num的平方根(num必须是大于等于0的数)

console.log(Math.sqrt(100));//10

【Math.pow(num,power)】返回num的power次幂

console.log(Math.pow(10,2));//100
posted @ 2021-09-29 11:33  wmui  阅读(194)  评论(0编辑  收藏  举报