基础方法 Math.max 和 Math.min

javascript 提供了 Math.max 和 Math.min 方法用于求数组中的最大值和最小值。

具体参数

Math.max Math.min
描述 都是 Math 对象的静态方法,不能作为你构建的 Math 实例的方法(Math 不是适构造函数)。
参数 [value1[, value2[, value3 ….]]]
返回值 返回给定数组中的最大(小)值,如何任意一参数不能转换为数值,则返回 NaN。
特殊情况 没有参数,则结果为 -Infinity。 没有参数,则结果为 Infinity。

例子(Math.max 为例)

  1. Math.max(true, 0); // 1
  2. Math.max(true, '2', null); // 2
  3. Math.max(1, undefined); // NaN
  4. Math.max(1, {}); // NaN
  5. const min = Math.min();
  6. const max = Math.max();
  7. console.log(min > max); // true

衍生方法

遍历

  1. const arr = [6, 4, 1, 8, 2, 11, 23];
  2. let result = arr[0];
  3. for (let i = 1; i < arr.length; i++) {
  4. result = Math.max(result, arr[i]);
  5. }
  6. console.log(result); // 23

reduce

  1. const arr = [6, 4, 1, 8, 2, 11, 23];
  2. function max(prev, next) {
  3. return Math.max(prev, next);
  4. }
  5. console.log(arr.reduce(max)); // 23

排序

  1. const arr = [6, 4, 1, 8, 2, 11, 23];
  2. arr.sort(function(a, b) {
  3. return a - b;
  4. });
  5. console.log(arr[arr.length - 1]); // 23

eval

  1. const arr = [6, 4, 1, 8, 2, 11, 23];
  2. const max = eval("Math.max(" + arr + ")");
  3. console.log(max); // 23

apply

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

… 拓展运算符

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

参考:

[1] Javascript 专题之如何求数组中的最大值和最小值