JavaScript中的Math对象提供了许多常用的数学方法和常量。以下是一些最常用的方法:
方法 | 说明 |
---|---|
max | 返回一组数中的最大值 |
min | 返回一组数中的最小值 |
round | 返回最接近的整数。 四舍五入 |
floor | 返回小于或等于x的最大整数。 向下取整 |
ceil | 返回大于或等于x的最小整数。 向上取整 |
abs | 返回x的绝对值。 |
sqrt | 返回x的平方根。 |
random | 返回一个介于0(包含)和1(不包含)之间的随机数。公式: Math.random()*(最大值-最小值+1)+最小值 |
PI | π的值,约为3.14159 |
1. Math.max(…values):
返回一组数中的最大值。
const maxNumber = Math.max(1, 5, 10, 2);
console.log(maxNumber); // 10
2. Math.min(…values):
返回一组数中的最小值。
const minNumber = Math.min(1, 5, 10, 2);
console.log(minNumber); // 1
3. Math.round(x):
返回最接近的整数。 四舍五入
const rounded = Math.round(4.7);
console.log(rounded); // 5
const roundedDown = Math.round(4.4);
console.log(roundedDown); // 4
4. Math.floor(x):
返回小于或等于x的最大整数。 向下取整
const floored = Math.floor(4.7);
console.log(floored); // 4
5. Math.ceil(x):
返回大于或等于x的最小整数。 向上取整
const ceiled = Math.ceil(4.7);
console.log(ceiled); // 5
6. Math.abs(x):
返回x的绝对值。
const absoluteValue = Math.abs(-5.7);
console.log(absoluteValue); // 5.7
7. Math.sqrt(x):
返回x的平方根。
const squareRoot = Math.sqrt(16);
console.log(squareRoot); // 4
8. Math.random():
返回一个介于0(包含)和1(不包含)之间的随机数。
const randomValue = Math.random();
console.log(randomValue); // 输出介于 0 和 1 之间的随机数,例如 0.5488135039273248
- 获取整数随机数
公式: (Math.random()*(最大值-最小值+1))+最小值
// 获取 1 - 10 的随机数
const randomValue = Math.floor(Math.random() * (10- 1+ 1)) + 1;
可以把这个公式封装成方法
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomNumber = getRandomNumber(1, 10);
console.log(randomNumber);
9. Math.PI:
π的值,约为3.14159。
const piValue = Math.PI;
console.log(piValue); // 3.141592653589793
这些只是一些常用的Math方法,还有其他更多的方法可以在需要时查阅JavaScript文档。