一文搞懂JavaScript数组中最难的数组API——reduce()
前面我们讲了数组的一些基本方法,今天给大家讲一下数组的reduce(),它是数组里面非常重要也是比较难的函数,那么这篇文章就好好给大家介绍下reduce函数。
还是老样子,我们直接在应用中学习,直接上例子。让我们先定义一个包含几个对象的数组,注意观察下这个数组,可以看到里面有两个对象的age都是30。(下面会用到)
| |
| const people = [ |
| { name: "John", age: 20 }, |
| { name: "Jane", age: 22 }, |
| { name: "Joe", age: 23 }, |
| { name: "Jack", age: 24 }, |
| { name: "Jackson", age: 30 }, |
| { name: "Jeff", age: 30 }, |
| ] |
1.求数组中所有对象的年龄和
通过数组的reduce方法可以很方便的实现求和。reduce方法有两个参数,第一个参数是一个回调函数,第二个参数是初始值。下面就讲下这两个参数,回调函数,有四个参数,函数体处理自己的逻辑。第二个参数,它的值决定回调函数第一个参数的初始值。重点就是这个初始值。(文末会详细介绍这几个参数)
| |
| |
| const sum = people.reduce((res, cur) => res+cur.age, 0) |
| console.log(`结果:${sum}`); |
| |
| const sum = people.reduce((res, cur) => res+cur.age, 100) |
| console.log(`结果:${sum}`); |
2.按照年龄分组(比如上面有两个人都是30岁,那么他们应该分在一起)
| const sum = people.reduce((res, cur) => { |
| |
| const age = cur.age |
| if (res[age] == null) { |
| |
| res[age] = [] |
| } |
| |
| res[age].push(cur.name) |
| return res |
| }, {}) |
| code1.png |
3.将数组对象转化为对象,name为key ,age为value
| |
| const sum = people.reduce((res, cur) => { |
| const name = cur.name |
| res[name]=cur.age |
| return res |
| }, {}) |
| |
| const sum = people.reduce((res, cur) => ({ |
| ...res, |
| [cur.name] : cur.age |
| }), {}) |
| |
| const sum = people.reduce((res, { name, age }) => ({ |
| ...res, |
| [name] : age |
| }), {}) |
| |
| console.log(sum) |
| image.png |
4.最后看下各个参数打印的结果,以及不写定义初始值的情况
| |
| const sum = people.reduce((res, cur, index, array) => { |
| console.log('🚀 ~ file: ~ res', res) |
| console.log('🚀 ~ file: ~ cur', cur) |
| console.log('🚀 ~ file: ~ index', index) |
| console.log('🚀 ~ file: ~ array', array) |
| return res + cur.age |
| }, 0) |

可以看到输出结果,第一个参数res等于初始值0
| const sum = people.reduce((res, cur, index, array) => { |
| console.log('🚀 ~ file: ~ res', res) |
| console.log('🚀 ~ file: ~ cur', cur) |
| console.log('🚀 ~ file: ~ index', index) |
| console.log('🚀 ~ file: ~ array', array) |
| return res + cur.age |
| }) |

5.总结下回调函数中的四个参数
第一个参数:
1.第一次迭代:当给了初始值时,它的初始值就为该值。然后通过该值去执行相关逻辑操作,第二次迭代它的值就为上次迭代的结果。后面依次类推。
2.第一次迭代:当没有给初始值时,它的初始值就是数组本身的第一个迭代对象。后续(同上)
建议:最好给一个初始值,因为它决定你最终需要什么类型的结果(它决定回调函数的第一个参数)。
第二个参数是当前迭代的对象;(1.当没有给初始值时,它的初始值就是数组本身的第一个迭代对象;2.当给了初始值时,它的初始值就是数组本身的第二个迭代对象)
第三个参数是第二个参数的索引
第四个参数是将要迭代的所有对象的数组(简单说就是数组本身)
对于reduce()我们只需要弄清楚其参数与返回值,那么基本就掌握该函数了。