关于数组最大值和最小值,我相信大家马上就能想到以下这个方法,这是JavaScript给我们的一个内置方法,简单实用!
Math.max() // or
Math.min()
但是今天给大家分享使用reduce去获取最大值和最小值的方法,不过在此之前呢?我会给大家先讲解一下reduce这个api,可能会有一些同学不太了解这个方法,然后我再讲解怎么实现求最大值和最小值
reduce
在语法中我们可以看到,reduce这个函数是以一个函数以及初始值组成,详细说明可见文档
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
total -- 必须。初始值, 或者计算结束后的返回值。
currentValue -- 必需。当前元素
currentIndex -- 可选。当前元素的索引
arr -- 可选。当前元素所属的数组对象。
initialValue -- 可选。传递给函数的初始值
大家在了解到这个函数方法以后,可能或多或少还不知道怎么使用,那我们就在使用中去了解他吧!
total是初始值,也是返回值;而currentValue为当前值(在没有initialValue传递初始值的时候,currentValue的值是索引 【1】 ;反之,【0】);
所以第一次的时候,是total(1)+ currentValue(2)
第二次:total(3)【这个3是返回值】+ currentValue(2)
结果就为5
const potatos = [1,2,2];
const size = potatos.reduce((total,currentValue)=>{return total + currentValue});
console.log(size); // 5
大家在了解到基本的概念以后,我们来打印一下,这样更加直观
const potatos = [1,2,2];
const size = potatos.reduce((total,currentValue)=>{
console.log(total + '我是total');
console.log(currentValue + '我是currentValue');
return total + currentValue});
console.log(size);
1我是total
2我是currentValue
3我是total
2我是currentValue
以上代码我们都是没有传递初始值的,我们写一个有初始值的代码,看看打印出来会是什么,同学们也都可以思考思考
const potatos = [1,2,2];
const size = potatos.reduce((total,currentValue)=>{
console.log(total + '我是total');
console.log(currentValue + '我是currentValue');
return total + currentValue},3);
console.log(size);
3我是total
1我是currentValue
4我是total
2我是currentValue
6我是total
2我是currentValue
同学们可以这样理解:如果没有传递初始值是total为索引为0的1(以及返回值),但是传值以后total就是你所传递的这个值(以及返回值),然后currentValue就从数组的第一个开始执行。
我想同学们在看到这儿的时候,对reduce函数已经有基本的了解了,那我们就开始说说我们怎么去实现最大值和最小值吧!
在reduce中total会去接收每一个返回值,那么我们做一个判断,如果currentValue值比total的值更小就赋值给total,反之就赋值其本身就好了
reduce方法不仅可以对一维数组有用,对二维数组还是可以的哦!
我将两个都写一遍供大家借鉴
const potatos = [4,1,2,2];
const size = potatos.reduce((total,currentValue)=>{return total > currentValue ? currentValue : total});
console.log(size); // 1
const potatos = [{id:12},{id:5},{id:2}];
const key = 'id';
const size = potatos.reduce((total,currentValue)=>{return total[key] > currentValue[key] ? currentValue : total})[key];
console.log(size); // 2
是不是相当的不错,如果是最大值,将大于符号转小于符号即可~
以前的文章
element-ui动态级联选择器回显问题,二十多行代码就可以搞定
以上就是本章的全部内容了!马上就要过年了,以后在新的一年同学们都有一个质的飞越。
授人与鱼不如授人以鱼!!!