JavaScript Math 对象常用方法详解

作者:代码拾荒时间:2026-10-21 20:11:33浏览:346

本文系统总结 JavaScript 中 Math 对象的常用方法。涵盖获取最大最小值的 min 和 max,执行向上、向下及标准舍入的 ceil、floor 和 round,生成指定范围随机数的 random 及其封装函数,以及绝对值、幂、对数、三角函数等其它数学运算方法,帮助开发者高效处理数值计算。

获取最大最小值:min() 与 max()

1. min() 和 max() 方法

Math.min() 函数用于从一组数值中找出最小值,而 Math.max() 函数则用于找出最大值。


alert(Math.min(2,4,3,6,3,8,0,1,3));              //最小值
alert(Math.max(4,7,8,3,1,9,6,0,3,2));         //最大值

数值舍入:ceil()、floor() 与 round()

2. 舍入方法

Math.ceil() 执行向上舍入操作,即始终将数值向上舍入到最接近的整数;

Math.floor() 执行向下舍入操作,即始终将数值向下舍入到最接近的整数;

Math.round() 执行标准四舍五入操作,即根据数值大小将其舍入到最接近的整数;

例如:


alert(Math.ceil(25.9));                   //26
alert(Math.ceil(25.5));                   //26
alert(Math.ceil(25.1));                   //26
alert(Math.floor(25.9));                  //25
alert(Math.floor(25.5));                  //25
alert(Math.floor(25.1));                  //25
alert(Math.round(25.9));                     //26
alert(Math.round(25.5));                     //26
alert(Math.round(25.1));                     //25

生成随机数:random() 及范围计算

3. random() 方法

Math.random() 方法返回一个介于 0 和 1 之间的随机数,不包含 0 和 1。如果需要生成更大范围的随机数,可以使用以下公式:

值 = Math.floor(Math.random() * 总数 + 第一个值)

例如:

alert(Math.floor(Math.random() * 10 + 1));        //随机产生1-10之间的任意数


for (var i = 0; i<10;i ++) {
    document.write(Math.floor(Math.random() * 10 + 5));       //5-14之间的任意数
    document.write('<br />');
}

为了更便捷地指定随机数的范围,可以将其封装为函数:


function selectFrom(lower, upper) {
    var sum = upper - lower + 1;                      //总数-第一个数+1
    return Math.floor(Math.random() * sum + lower);
}
for (var i=0 ;i<10;i++) {
    document.write(selectFrom(5,10));                 //直接传递范围即可
    document.write('<br />');
}

其他数学运算方法

4. 其它方法

如下表格:

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持本站!

方  法

说  明

Math.abs(num)

返回num的绝对值

Math.exp(num)

返回Math.E的num次幂

Math.log(num)

返回num的自然对数

Math.pow(num,power)

返回num的power次幂

Math.sqrt(num)

返回num的平方根

Math.acos(x)

返回x的反余弦值

Math.asin(x)

返回x的反正弦值

Math.atan(x)

返回x的反正切值

Math.atan2(y,x)

返回y/x的反正切值

Math.cos(x)

返回x的余弦值

Math.sin(x)

返回x的正弦值

Math.tan(x)

返回x的正切值

作者最新文章