JS标准库之Math对象
Math是 JavaScript 的原生对象,提供各种数学功能。该对象不是构造函数,不能生成实例,所有的属性和方法都必须在 Math 对象上调用。
静态属性
提供一些数学常数
Math.E:常数eMath.LN2:2 的自然对数Math.LN10:10 的自然对数Math.LOG2E:以 2 为底的e的对数Math.LOG10E:以 10 为底的e的对数Math.PI:常数πMath.SQRT1_2:0.5 的平方根Math.SQRT2:2的平发根
|
1 2 3 4 5 6 7 8 |
Math.E // 2.718281828459045 Math.LN2 // 0.6931471805599453 Math.LN10 // 2.302585092994046 Math.LOG2E // 1.4426950408889634 Math.LOG10E // 0.4342944819032518 Math.PI // 3.141592653589793 Math.SQRT1_2 // 0.7071067811865476 Math.SQRT2 // 1.4142135623730951 |
这些属性都是只读的,不能修改
静态方法
Math.abs():绝对值Math.ceil():向上取整Math.floor():向下取整Math.max():最大值Math.min():最小值Math.pow():幂运算Math.sqrt():平方根Math.log():自然对数Math.exp():e的指数Math.round():四舍五入Math.random():随机数
Math.abs()
返回参数值的绝对值
|
1 2 |
Math.abs(1) // 1 Math.abs(-1) // 1 |
Math.max(),Math.min()
Math.max方法返回参数之中最大的那个值,Math.min返回最小的那个值。Math.min返回Infinity,Math.max返回-Infinity。
|
1 2 3 4 |
Math.max(2, -1, 5) // 5 Math.min(2, -1, 5) // -1 Math.min() // Infinity Math.max() // -Infinity |
Math.floor(),Math.ceil()
Math.floor方法返回小于或等于参数值的最大整数(地板值)。
|
1 2 |
Math.floor(3.2) // 3 Math.floor(-3.2) // -4 |
Math.ceil方法返回大于或等于参数值的最大整数(天花板值)。
|
1 2 |
Math.ceil(3.2) // 4 Math.ceil(-3.2) // -3 |
Math.round()
Math.round方法用于四舍五入。
|
1 2 3 4 5 6 7 8 |
Math.round(0.1) // 0 Math.round(0.5) // 1 Math.round(0.6) // 1 // 注意对负数0.5的处理 Math.round(-1.1) // -1 Math.round(-1.5) // -1 Math.round(-1.6) // -2 |
Math.pow()
Math.pow方法返回以第一个参数为底数,第二个参数为指数的幂运算值。
|
1 |
Math.pow(2, 3) // 8 等同于 2**3 |
Math.sqrt()
Math.sqrt()方法返回参数值的平方根。如果参数是一个负值,则返回NaN。
|
1 2 |
Math.sqrt(4) // 2 Math.sqrt(-4) // NaN |
Math.log()
Math.log()方法返回以e为底的自然对数值。
|
1 2 |
Math.log(Math.E) // 1 Math.log(10) // 2.302585092994046 |
Math.exp()
Math.exp()方法返回常数e的参数次方。
|
1 2 |
Math.exp(1) // 2.718281828459045 Math.exp(3) // 20.085536923187668 |
Math.random()
Math.random()返回0到1之间的一个伪随机数,可能等于0,但是一定小于1。
|
1 |
Math.random() // 0.7151307314634323 |
任意范围的随机数生成函数如下:
|
1 2 3 4 5 6 |
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } getRandomArbitrary(1.5, 6.5) // 2.4942810038223864 |
任意范围的随机整数生成函数如下:
|
1 2 3 4 5 |
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } getRandomInt(1, 6) // 5 |
三角函数方法
Math对象还提供一系列三角函数方法。
Math.sin():返回参数的正弦(参数为弧度值)Math.cos():返回参数的余弦(参数为弧度值)Math.tan():返回参数的正切(参数为弧度值)Math.asin():返回参数的反正弦(返回值为弧度值)Math.acos():返回参数的反余弦(返回值为弧度值)Math.atan():返回参数的反正切(返回值为弧度值)
|
1 2 3 4 5 6 7 8 9 |
Math.sin(0) // 0 Math.cos(0) // 1 Math.tan(0) // 0 Math.sin(Math.PI / 2) // 1 Math.asin(1) // 1.5707963267948966 Math.acos(1) // 0 Math.atan(1) // 0.7853981633974483 |
这些信息可能会帮助到你: 关于我们 | 侵权删除 | 捐赠支持
优惠推广:外卖红包天天领,下单享返钱奖励~文章名称:JS标准库之Math对象
文章链接:https://www.bysjb.cn/js-library-math.html
THE END
二维码
打赏

共有 0 条评论