如何求数组的最大值
前言
我这里罗列下求数组最大值的几种方案。
Math.max
Math.max() 函数返回一组数中的最大值。
注意:
- 由于 max 是 Math 的静态方法,所以应该像这样使用:
Math.max()
,而不是创建的 Math 实例的方法(Math 不是构造函数)。 - 如果没有参数,则结果为 -Infinity,与之对应的
Math.min()
没有传入参数,则结果为 Infinity。 - 如果有任一参数不能被转换为数值,则结果为 NaN。
- 如果参数不是数值类型,那么转换类型后再进行比较。
举个例子:
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()
方法求数组最大值。
apply
let arr = [1, 2, 3, 5, 8, 9]
let max = Math.max.apply(null, arr)
console.log(max) // 9
ES6 扩展运算符
let arr = [1, 2, 3, 5, 8, 9]
let max = Math.max(...arr)
console.log(max) // 9
eval
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
接下来结合遍历数组的方法求数组的最大值。
for 循环
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
reduce
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
结语
本文到这里就结束了。以上几种求数组最大值的方案,就当做是自己的学习笔记。在未来开发中,结合场景适当使用上述方法。