JavaScript中Math常用方法

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文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

&白帝&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值