// 获取数组最大值的示例代码
// 方法一:使用 Math.max() 和 spread 运算符
const numbers = [1, 3, 5, 7, 9];
const maxNumber = Math.max(...numbers);
console.log(maxNumber); // 输出: 9
// 解释说明:
// Math.max() 函数返回一组数中的最大值。
// 使用 spread 运算符 (...) 可以将数组元素展开为单独的参数传递给 Math.max()。
// 方法二:使用 reduce() 方法
const numbers2 = [2, 4, 6, 8, 10];
const maxNumber2 = numbers2.reduce((max, current) => (current > max ? current : max), numbers2[0]);
console.log(maxNumber2); // 输出: 10
// 解释说明:
// reduce() 方法对数组中的每个元素(从左到右)执行一个 reducer 函数,将其结果汇总为单个返回值。
// 在这个例子中,reducer 函数比较当前元素和累积的最大值,并返回较大的那个。
上一篇:js 获取数组最后一个
下一篇:js 获取数组的长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站