js reduce 计算最大值、最小值

发布时间: 2022-06-03 22:19:20 作者: 大象笔记

示例代码

const maxWidth = imgs.reduce((m, x) => Math.max(m, x.width), 0);

其功能是计算一组图片的最大宽度。

但是看起来很难理解。

可读性更好的 reduce 用法

const maxWidth = imgs.reduce(
	(previousValue, img) => Math.max(previousValue, img.width),
	0
);

其实就是遍历数组中的每一项,通过函数逐一比对,最终返回一个最大/小值。

reduce 参数说明

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce 接受两个参数

参数一的函数可以接受4个参数,但通常只用到前两个。参考:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

示例代码二

例如,我最近写了个核酸检测报告在线拼图的小工具,其首先要计算多张图片的最小高度。这里就用到了 array reduce:

const imgs = await this.loadImages(urls);

const minHeight = imgs.reduce(
  (previousValue, img) => Math.min(previousValue, img.height),
  Number.MAX_VALUE,
);
我是一名山东烟台的开发者,联系作者