JavaScript 中的 Math
对象提供了一组用于数学计算的方法和常量。以下是一些常用的 Math
方法:
Math.abs(x)
:返回数值x
的绝对值。
Math.abs(-3); // 返回 3
Math.ceil(x)
:将数值x
向上取整为最接近的整数。
Math.ceil(4.2); // 返回 5
Math.floor(x)
:将数值x
向下取整为最接近的整数。
Math.floor(4.8); // 返回 4
Math.round(x)
:将数值x
四舍五入为最接近的整数。
Math.round(4.5); // 返回 5
Math.max(x1, x2, ..., xn)
:返回一系列数值中的最大值。
Math.max(2, 6, 3, 9); // 返回 9
Math.min(x1, x2, ..., xn)
:返回一系列数值中的最小值。
Math.min(2, 6, 3, 9); // 返回 2
Math.random()
:返回一个大于等于 0 且小于 1 的随机数。
Math.random(); // 返回 0 到 1 之间的随机小数,如 0.5473292381543418
Math.pow(x, y)
:返回x
的y
次幂(x^y)
Math.pow(2, 3); // 返回 8