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
我这里罗列下求数组最大值的几种方案。
Math.max() 函数返回一组数中的最大值。
注意:
Math.max()
Math.min()
举个例子:
let max1 = Math.max(1, 2) let max2 = Math.max(1, undefined) let max3 = Math.max() let max4 = Math.max(0, true) let min = Math.min() console.log(max1) // 2 console.log(max2) // NaN console.log(max3) // -Infinity console.log(max4) // 1 console.log(min) // Infinity
接下来结合 Math.max() 方法求数组最大值。
let arr = [1, 2, 3, 5, 8, 9] let max = Math.max.apply(null, arr) console.log(max) // 9
let arr = [1, 2, 3, 5, 8, 9] let max = Math.max(...arr) console.log(max) // 9
let arr = [1, 2, 3, 5, 8, 9] let max = eval('Math.max('+ arr +')') // => Math.max(1, 2, 3, 5, 8, 9) console.log(max) // 9
接下来结合遍历数组的方法求数组的最大值。
let arr = [1, 2, 3, 5, 8, 9] let res = arr[0] for (let i = 1, len = arr.length; i < len; i++) { res = Math.max(res, arr[i]) } console.log(res) // 9
let arr = [1, 2, 3, 5, 8, 9] let res = arr.reduce(function (acc, cur) { return Math.max(acc, cur) }) console.log(res) // 9
对数组进行升序后,那么最后一个值将是最大值。
let arr = [1, 2, 3, 5, 8, 9] arr.sort(function (a, b) { return a - b }) console.log(arr[arr.length - 1]) // 9
本文到这里就结束了。以上几种求数组最大值的方案,就当做是自己的学习笔记。在未来开发中,结合场景适当使用上述方法。
JavaScript专题之如何求数组的最大值和最小值
The text was updated successfully, but these errors were encountered:
No branches or pull requests
如何求数组的最大值
前言
我这里罗列下求数组最大值的几种方案。
Math.max
注意:
Math.max()
,而不是创建的 Math 实例的方法(Math 不是构造函数)。Math.min()
没有传入参数,则结果为 Infinity。举个例子:
接下来结合
Math.max()
方法求数组最大值。apply
ES6 扩展运算符
eval
接下来结合遍历数组的方法求数组的最大值。
for 循环
reduce
排序
对数组进行升序后,那么最后一个值将是最大值。
结语
本文到这里就结束了。以上几种求数组最大值的方案,就当做是自己的学习笔记。在未来开发中,结合场景适当使用上述方法。
参考文献
JavaScript专题之如何求数组的最大值和最小值
The text was updated successfully, but these errors were encountered: