基础方法 Math.max 和 Math.min
javascript 提供了 Math.max 和 Math.min 方法用于求数组中的最大值和最小值。
具体参数
| Math.max | Math.min | |
|---|---|---|
| 描述 | 都是 Math 对象的静态方法,不能作为你构建的 Math 实例的方法(Math 不是适构造函数)。 | |
| 参数 | [value1[, value2[, value3 ….]]] | |
| 返回值 | 返回给定数组中的最大(小)值,如何任意一参数不能转换为数值,则返回 NaN。 | |
| 特殊情况 | 没有参数,则结果为 -Infinity。 | 没有参数,则结果为 Infinity。 | 
例子(Math.max 为例)
Math.max(true, 0); // 1Math.max(true, '2', null); // 2Math.max(1, undefined); // NaNMath.max(1, {}); // NaNconst min = Math.min();const max = Math.max();console.log(min > max); // true
衍生方法
遍历
const arr = [6, 4, 1, 8, 2, 11, 23];let result = arr[0];for (let i = 1; i < arr.length; i++) {result = Math.max(result, arr[i]);}console.log(result); // 23
reduce
const arr = [6, 4, 1, 8, 2, 11, 23];function max(prev, next) {return Math.max(prev, next);}console.log(arr.reduce(max)); // 23
排序
const arr = [6, 4, 1, 8, 2, 11, 23];arr.sort(function(a, b) {return a - b;});console.log(arr[arr.length - 1]); // 23
eval
const arr = [6, 4, 1, 8, 2, 11, 23];const max = eval("Math.max(" + arr + ")");console.log(max); // 23
apply
const arr = [6, 4, 1, 8, 2, 11, 23];console.log(Math.max.apply(null, arr)); // 23
… 拓展运算符
const arr = [6, 4, 1, 8, 2, 11, 23];console.log(Math.max(...arr)); // 23
参考:
