用JS寻找数组中的最大、最小值

239 阅读1分钟

有这么一道题,已知整数数组a,找出其中的最大值与最小值,用尽可能多的方法去实现。

let a = [4, 2, 3, 2, 1, 5, 0]

暴力循环

// 第一种写法
const max = function(arr) {
    let res = 0;
    arr.forEach(e => {
        res = Math.max(res, e);
    })

    return res;
}

// 第二种写法
const max = function(arr) {
    return arr.reduce((p, c) => Math.max(p, c));
}

排序法

const max = function(arr) {
    let str = JSON.parse(JSON.stringify(arr)); 
    str.sort();

    return str[str.length - 1];
}

使用apply

const max = function(arr) {
    return Math.max.apply(null, arr);
}

ES6 拓展符

const max = function(arr) {
    return Math.max(...arr);
}