Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取数组最大值

作者:刃起风啸凌   发布日期:2026-04-12   浏览:21

// 获取数组最大值的示例代码

// 方法一:使用 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 获取数组的长度

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站