当我们要对数字进行一些复杂的操作或计算时,js语言内置的 Math
对象是不可或缺的一个工具。Math
对象提供了很多有用的方法来处理数字。
常用方法
Math.abs()
Math.abs()
方法用于返回给定数字的绝对值,即该数字距离 0 的距离,无论正负。
Math.abs(-5); // 返回 5
Math.abs(5); // 返回 5
Math.abs('-5'); // 返回 5
Math.abs('5'); // 返回 5
Math.ceil()
Math.ceil()
方法向上取整一个数字,即返回一个大于或等于该数字的最小整数。
Math.ceil(2.4); // 返回 3
Math.ceil(2.8); // 返回 3
Math.ceil(-2.4); // 返回 -2
Math.ceil(-2.8); // 返回 -2
Math.floor()
Math.floor()
方法向下取整一个数字,即返回一个小于或等于该数字的最大整数。
Math.floor(2.4); // 返回 2
Math.floor(2.8); // 返回 2
Math.floor(-2.4); // 返回 -3
Math.floor(-2.8); // 返回 -3
Math.max()
Math.max()
方法用于返回给定数字中的最大值。
Math.max(1, 2, 3, 4, 5); // 返回 5
Math.max(-1, -2, -3, -4, -5); // 返回 -1
Math.min()
Math.min()
方法用于返回给定数字中的最小值。
Math.min(1, 2, 3, 4, 5); // 返回 1
Math.min(-1, -2, -3, -4, -5); // 返回 -5
Math.pow()
Math.pow()
方法用于计算一个数的指定次幂。
Math.pow(2, 3); // 返回 8
Math.pow(10, -2); // 返回 0.01
Math.random()
Math.random()
方法返回一个随机数,该随机数在 0 到 1 之间。这个方法通常被用作生成随机数。
Math.random(); // 返回介于0(包括)和1(不包括)之间的随机数
Math.round()
Math.round()
方法用于四舍五入一个数字。
Math.round(2.4); // 返回 2
Math.round(2.5); // 返回 3
Math.round(2.8); // 返回 3
Math.round(-2.4); // 返回 -2
Math.round(-2.5); // 返回 -2
Math.round(-2.8); // 返回 -3
Math.sqrt()
Math.sqrt()
方法用于计算一个数字的平方根。
Math.sqrt(16); // 返回 4
Math.sqrt(2); // 返回 1.414213...
示例说明
示例一
假设我们要编写一个函数来随机生成一个在某个范围内的数,可以使用 Math.random()
方法。
首先,我们需要确定生成的最小值和最大值。例如,我们要在 1 和 10 之间生成一个随机数。
function randomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randomNum(1, 10));
上述函数中,在 Math.random()
方法的返回值上乘以 (max - min + 1)
,然后使用 Math.floor()
向下取整,最后加上 min
,即可生成一个在 min
和 max
之间的随机整数。
示例二
假设我们要编写一个函数来计算两个点之间的距离。我们可以使用 Math.pow()
方法来求平方,并结合 Math.sqrt()
方法来获得距离。
function distance(x1, y1, x2, y2) {
const xDistance = x2 - x1;
const yDistance = y2 - y1;
return Math.sqrt(Math.pow(xDistance, 2) + Math.pow(yDistance, 2));
}
console.log(distance(1, 2, 4, 6)); // 返回 5.0
上述函数中,我们首先计算 x 和 y 轴之间的距离,然后使用 Math.pow()
计算平方,接着使用 Math.sqrt()
方法求平方根即可得到最终的距离。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:js Math 对象的方法 - Python技术站