我的github

Array.prototype.reduce() 是数组中最强大的方法之一,也是 JavaScript 函数式编程中一个吸引人的特性。但不幸的是,我发现很多朋友不习惯使用它

这是 reduce 的基本用法:

var arr = [1, 2, 3];
function reducer(parmar1, parmar2){
}
arr.reduce(reducer)

reduce是数组原型对象上的一个方法,可以帮助我们操作数组。它将另一个函数作为其参数,可以称为reducer。

参考:https://www.jb51.net/article/254405.htm

使用reduce求js查找数组最大值:

参考2:https://cloud.tencent.com/developer/information/js查找数组最大值

const array = [1, 2, 3, 4, 5];
const max = array.reduce((a, b) => (a > b ? a : b), array[0]);
console.log(max); // 输出: 5

解释

  • reduce 方法遍历数组,每次比较当前元素和累积值,保留较大的那个。
  • 初始值设为数组的第一个元素 array[0]
posted on 2023-06-28 09:56  XiaoNiuFeiTian  阅读(20)  评论(0)    收藏  举报