总结几种求数组最大值的方法

149 阅读1分钟

1.擂台思想

 let arr = [20,50,66,100,30]
 
 let max = arr[0]
    for(let i = 1;i<arr.length;i++){
        if( arr[i] > max ){
            max = arr[i]
        }
    }
    console.log(max)

2.Math.max()

// let max1 = Math.max(arr[0],arr[1],arr[2],arr[3],arr[4])
//这里使用apply只是借助传参特点,this指向不用修改。还是原来的this
let max1 = Math.max.apply(Math,arr)
console.log( max1 )

3.reduce

let arr = [20, 55, 80, 70, 92, 35];

function max(prev, next) {
    return Math.max(prev, next);
}
console.log(arr.reduce(max));

4.排序

如果我们先对数组进行一次排序,那么最大值就是最后一个值

let arr = [6, 4, 1, 8, 2, 11, 23];

arr.sort(function(a,b){return a - b;});
console.log(arr[arr.length - 1])

5.ES6

使用ES6的拓展运算符

let arr = [6, 4, 1, 8, 2, 11, 23];
console.log(Math.max(...arr))