求js数组最大值

发布时间 2023-07-13 14:04:11作者: 青老师
1 let arr = [1, 2, 3, 4, 5]
2 
3 let max = arr.reduce((prev, cur) => {
4   return Math.max(prev, cur)
5 })
6 
7 console.log(max) // expected output: 5

 

// 找出数组中最大/小的数字
const numbers = [5, 6, 2, 3, 7];

// 使用 Math.min/Math.max 以及 apply 函数时的代码
let max = Math.max.apply(null, numbers); // 基本等同于 Math.max(numbers[0], ...) 或 Math.max(5, 6, ..)
let min = Math.min.apply(null, numbers);

// 对比:简单循环算法
max = -Infinity, min = +Infinity;
for (let i = 0; i < numbers.length; i++) { if (numbers[i] > max) max = numbers[i]; if (numbers[i] < min) min = numbers[i]; }

  

let arr = [1,2,3,6,7,8]

Math.max(...arr)
8