JavaScript的Math对象是一个内置对象,提供了用于执行数学任务的方法和属性。下面是一些常用的Math对象方法:
数值运算函数:
- abs(x)
- ceil(x)
- floor(x)
- max(x,y,z,...,n)
- min(x,y,z,...,n)
- pow(x,y)
- round(x)
- sqrt(x)
- trunc(x)
这些函数用于常见的数值运算,例如取绝对值、向上取整、向下取整、求最大值、求最小值、幂运算、四舍五入、求平方根等。
三角函数和反三角函数:
- acos(x)
- asin(x)
- atan(x)
- atan2(y,x)
- cos(x)
- sin(x)
- tan(x)
这些函数用于处理角度和三角函数计算,包括反余弦、反正弦、反正切、余弦、正弦和正切函数。
指数和对数函数:
- exp(x)
- log(x)
exp(x) 返回 Euler 数 (e) 的指数形式,log(x) 返回 x 的自然对数(底为 e)。
随机数函数:
- random()
random() 返回 0 到 1 之间的随机数。
双曲函数:
- tanh(x)
tanh(x) 返回一个数的双曲正切函数值。
示例代码
let x = -5.6;// 数值运算函数
let absX = Math.abs(x); // absX = 5.6,取x的绝对值
let ceilX = Math.ceil(x); // ceilX = -5,向上取整
let floorX = Math.floor(x); // floorX = -6,向下取整
let maxValue = Math.max(10, 20, 30); // maxValue = 30,求最大值
let minValue = Math.min(10, 20, 30); // minValue = 10,求最小值
let power = Math.pow(2, 3); // power = 8,计算2的3次方
let rounded = Math.round(3.14159); // rounded = 3,四舍五入
let sqrtX = Math.sqrt(16); // sqrtX = 4,计算平方根
let truncated = Math.trunc(9.8); // truncated = 9,截取整数部分// 三角函数和反三角函数
let cosX = Math.cos(Math.PI); // cosX = -1,计算余弦值,这里使用了π
let sinX = Math.sin(Math.PI); // sinX = 0,计算正弦值,这里使用了π
let tanX = Math.tan(Math.PI/4); // tanX = 1,计算正切值,这里使用了π/4
let acosX = Math.acos(0.5); // acosX = 60°,计算反余弦值,返回结果的单位为弧度
let asinX = Math.asin(0.5); // asinX = 30°,计算反正弦值,返回结果的单位为弧度
let atanX = Math.atan(1); // atanX = 45°,计算反正切值,返回结果的单位为弧度
let atan2XY = Math.atan2(1, 1); // atan2XY = 45°,计算点 (1, 1) 相对于原点的极坐标角度,返回结果的单位为弧度// 指数和对数函数
let expX = Math.exp(2); // expX = e^2 ≈ 7.389,计算自然指数e的平方
let logX = Math.log(10); // logX ≈ 2.303,计算以e为底的对数// 随机数函数
let randomNumber = Math.random(); // 返回0到1之间的随机数// 双曲函数
let tanhX = Math.tanh(0.5); // tanhX ≈ 0.462,计算双曲正切值