We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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 提供了 Math.max 函数返回一组数中的最大值,用法是:
Math.max([value1[,value2, ...]])
值得注意的是:
Math.max()
循环:
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 专题之如何求数组的最大值和最小值
The text was updated successfully, but these errors were encountered:
No branches or pull requests
如何求数组的最大值和最小值
JavaScript 提供了 Math.max 函数返回一组数中的最大值,用法是:
值得注意的是:
Math.max()
,而不是作为 Math 实例的方法 (简单的来说,就是不使用 new )循环:
reduce:
排序 sort:
eval:
apply:
ES6:
原文地址:JavaScript 专题之如何求数组的最大值和最小值
The text was updated successfully, but these errors were encountered: