使用 Math 方法获取数组最值
通过 apply 和扩展运算符让 Math.max/min 处理数组
问题
如何使用 Math.max() 和 Math.min() 获取数组中的最大值和最小值?
解答
Math.max() 和 Math.min() 只接受多个参数,不能直接传入数组:
console.log(Math.min(1, 5, 2, 7, 3)); // 1
console.log(Math.max(1, 5, 2, 7, 3)); // 7
要处理数组,可以使用以下两种方法:
方法一:apply
const arr = [1, 5, 2, 7, 3];
console.log(Math.min.apply(null, arr)); // 1
console.log(Math.max.apply(null, arr)); // 7
方法二:扩展运算符
const arr = [3, 5, 1, 6, 2, 8];
const minVal = Math.min(...arr); // 1
const maxVal = Math.max(...arr); // 8
关键点
Math.max/min不接受数组参数,只接受多个独立参数apply方法可以将数组展开为参数列表- 扩展运算符
...是更现代的语法,推荐使用 - 两种方法本质都是将数组元素展开为独立参数
目录