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

经常使用方法

1.min()和max()方法es6

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

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

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

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

2.round()方法dom

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

Math.round(3.4) 返回值为3
Math.round(3.6) 返回值为4
复制代码

3.floor()方法spa

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

Math.floor(3.5)  返回值为3
复制代码

4.ceil()方法排序

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

Math.ceil(3.2) 返回值为4
复制代码

5.random()方法class

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)
复制代码
相关文章
相关标签/搜索