笔记6|青训营

50 阅读2分钟

Math 对象是 JavaScript 的内置对象之一,提供了执行数学运算的方法和属性。它不是一个构造函数,因此不需要使用 new 运算符来创建 Math 对象的实例。Math 对象中的所有方法和属性都是静态的,可以直接通过 Math 对象访问。

常用方法

  1. Math.abs()

Math.abs() 方法返回一个数的绝对值。例如: Math.abs(-10); // 返回 10 Math.abs(5); // 返回 5

  1. Math.ceil()

Math.ceil() 方法向上取整,返回大于或等于给定数字的最小整数。例如: Math.ceil(4.3); // 返回 5 Math.ceil(3.8); // 返回 4

  1. Math.floor()

Math.floor() 方法向下取整,返回小于或等于给定数字的最大整数。例如: Math.floor(4.3); // 返回 4 Math.floor(3.8); // 返回 3

  1. Math.max()

Math.max() 方法返回一组数中的最大值。例如: Math.max(1, 2, 3); // 返回 3 Math.max(-1, -2, -3); // 返回 -1 Math.max(10, 5, 8, 15); // 返回 15

  1. Math.min()

Math.min() 方法返回一组数中的最小值。例如: Math.min(1, 2, 3); // 返回 1 Math.min(-1, -2, -3); // 返回 -3 Math.min(10, 5, 8, 15); // 返回 5

  1. Math.pow()

Math.pow() 方法返回一个数的指定次幂。例如: Math.pow(2, 3); // 返回 8 Math.pow(5, 2); // 返回 25

  1. Math.random()

Math.random() 方法返回一个介于 0(包含)和 1(不包含)之间的随机浮点数。例如: Math.random(); // 返回一个介于 0 和 1 之间的随机数

  1. Math.round()

Math.round() 方法四舍五入为最接近的整数。例如: Math.round(4.3); // 返回 4 Math.round(3.8); // 返回 4

  1. Math.sqrt()

Math.sqrt() 方法返回一个数的平方根。例如: Math.sqrt(4); // 返回 2 Math.sqrt(9); // 返回 3

常用常量

  1. Math.PI

Math.PI 属性返回圆周率 π 的近似值 3.141592653589793。

  1. Math.E

Math.E 属性返回自然对数的底数 e 的近似值 2.718281828459045。

总结: Math 对象在 JavaScript 中提供了一系列用于数学运算的方法和常量。它可以帮助我们进行数值的计算和处理。本文介绍了 Math 对象的常用方法和常量,包括取整、绝对值、最大值、最小值、平方、平方根等。熟练使用 Math 对象的方法和常量,可以提高 JavaScript 编程的效率和准确性。