Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript专题之如何求数组的最大值和最小值 #53

Open
yangtao2o opened this issue Apr 3, 2020 · 0 comments
Open

JavaScript专题之如何求数组的最大值和最小值 #53

yangtao2o opened this issue Apr 3, 2020 · 0 comments

Comments

@yangtao2o
Copy link
Owner

yangtao2o commented Apr 3, 2020

如何求数组的最大值和最小值

JavaScript 提供了 Math.max 函数返回一组数中的最大值,用法是:

Math.max([value1[,value2, ...]])

值得注意的是:

  • 如果有任一参数不能被转换为数值,则结果为 NaN。
  • max 是 Math 的静态方法,所以应该像这样使用:Math.max(),而不是作为 Math 实例的方法 (简单的来说,就是不使用 new )
  • 如果没有参数,则结果为 -Infinity (注意是负无穷大)

循环

function max(arr) {
  var res = arr[0];
  for (var i = 1, len = arr.length; i < length; i++) {
    res = Math.max(res, arr[i]);
  }
  return res;
}

reduce

let getMax = arr => arr.reduce((prev, next) => Math.max(prev, next));

排序 sort

// a > b, a 和 b 交换位置,数组原地以升序排列
var getMax = arr => arr.sort((a, b) => a - b)[arr.length - 1];

eval

var max = eval("Math.max(" + arr + ")");
// arr + "" <= 这里隐式转换,一般要先转换成基本数据类型
console.log([1,2,3] + "");  // "1,2,3"
console.log("Math.max(" + [1,2,3] + ")")  // "Math.max(1,2,3)"

apply

var getMax = arr => Math.max.apply(null, arr);

ES6

var getMax = arr => Math.max(...arr);

原文地址:JavaScript 专题之如何求数组的最大值和最小值

@yangtao2o yangtao2o created this issue from a note in JavaScript 专题系列 (In progress) Apr 3, 2020
@yangtao2o yangtao2o moved this from In progress to Done in JavaScript 专题系列 Apr 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Development

No branches or pull requests

1 participant