js获取最大值的7种方式,不看不知道还可以这样实现

269 阅读1分钟

方式1:通过扩展预算符

Math.max(...[1,2,10,3,7]) // 10
// 或
Math.max.call(Math, ...[1,2,10,3,7]) // 10 

方式2:通过apply

Math.max.apply(Math, [1,2,10,3,7]) // 10

方式3:通过Reflect

Reflect.apply(Math.max, Math, [1,2,10,3,7]) // 10

方式4:通过sort

[1,2,10,3,7].sort((a, b) => a - b).pop() // 10

方式5:通过forEach循环判断(forfor infor of都可以)

const arr = [1,2,10,3,7];
let max = arr[1];
arr.forEach(val => {
    if(max < val) {
        max = val;
    }
});
console.log(max) // 10

方式6:通过reduce

const arr = [1,2,10,3,7];
const maxVal = arr.reduce((max, val) => {
    if(max < val) {
        max = val;
    }
    return max;
}, arr[1]);
console.log(maxVal) // 10

简写:

const arr = [1, 7, 3]
const max = arr.reduce((a, b) => a > b ? a : b)
console.log(max) // 7

方式7:通过reduceRight

const arr = [1,2,10,3,7];
const maxVal = arr.reduceRight((max, val) => {
    if(max < val) {
        max = val;
    }
    return max;
}, arr[0]);
console.log(maxVal) // 10

最小值同理,使用 Math.min 方法

更多前端技巧,请关注下图小程序

image.png