JS中的Math函数+取一个数组中的最大值

2,003 阅读1分钟

常用方法

1.min()和max()方法

Math.min()用于确定一组数值中的最小值。

 Math.min(23,45,6,2,4,5,234,6,45)  返回值为2

Math.max()用于确定一组数值中的最大值。

 Math.max(23,45,6,2,4,5,234,6,45) 返回值为234

2.round()方法

Math.round()将数值四舍五入为最接近的整数

Math.round(3.4) 返回值为3
Math.round(3.6) 返回值为4

3.floor()方法

Math.floor() 将数值向下取整

Math.floor(3.5)  返回值为3

4.ceil()方法

Math.ceil()将数值向上取整

Math.ceil(3.2) 返回值为4

5.random()方法

Math.random()取[0-1)之间的随机数 包含0不包含1
Math.random()*9 取[0-9) 之间的随数 包含0不包含9
Math.random()*(m-n)+n 取[n-m) 之间的随机数 包含n不包含m
Math.round(Math.random()*(m-n)+n) [n-m]之间的随机整数 包含n也包含m

6.abs()方法

Math.abs() 返回值为绝对值

Math.abs(-2) 返回值为2

7.sqrt()方法

Math.sqrt()返回值为开方

Math.sqrt(9) 返回值为3

8.pow()方法

Math.pow(x,y) 返回值为x的y次方
Math.pow(3,3) 返回值为27

怎么取一个数组中的最大值

1.用Math函数取一个数组中的最大值

var ary=[5,6,88,5,6,8,4,8,9,10,25];
es6的解构(...ary)解构就理解成 把外边的中括号给去掉了;
Math.max(...ary)

2.假设法+循环

    var ary=[5,6,88,5,6,8,4,8,9,10,25];
    var max=ary[0]
    for(var i=1;i<ary.length;i++){
        max>ary[i]?null:max=ary[i]
    }
    console.log(max);

3.先排序 再取值

var ary=[5,6,88,5,6,8,4,8,9,10,25];
    var arr=ary.sort((a,b)=>b-a)
    res=arr[0]
    console.log(res)