这篇博客是在2020时写的,现在再看感觉确实写的不好,甚至有很多错误,怕误导他人,于是在2022重写了一次。
1.官方文档
首先看一下官方文档,效果更佳
这是两年前的官方文档(2020年)
现在文档则已更新为:(2022)
2、解读:
reduce其实只有两个参数callback、initialValue:
第一个参数是callback回调函数,它里面又有previousValue(accumulator)、currentValue、index、array这四个参数。其实只需要关注前面两个参数previousValue、currentValue,后面两个用的比较少。数组里的每一项元素都会执行一次callback。这里面值得特别说的是previousValue(也有人叫它accumulator)即上一次的值。而currentValue则是这次callback正在处理的值。
第二个参数initialValue初始值。如果传入的话,那么第一次调用callback的时候,previousValue就是initialValue,currentValue则是数组下标为0的元素。如果没有传入,那么第一次回调的时候,previousValue就是下标0的元素,currentValue则是下标为1的元素。
其实还是差不多的,accumulator改成了previousValue而已,用法都是一样的。
3、举例子
借鉴:https://juejin.im/post/5cfcaa7ae51d45109b01b161#comment
这位大佬的处理方法很妙,但是我一眼看过去没有明白,细细琢磨了下,终于明白了
1 const userList = [ 2 { 3 id: 1, 4 username: 'john', 5 sex: 1, 6 email: 'john@163.com' 7 }, 8 { 9 id: 2, 10 username: 'jerry', 11 sex: 1, 12 email: 'jerry@163.com' 13 }, 14 { 15 id: 3, 16 username: 'nancy', 17 sex: 0, 18 email: '' 19 } 20 ]; 21 22 const userObj = userList.reduce((acc, person) => { 23 return {...acc, [person.id]: person} 24 }, {}) 25 26 console.log(userObj)
1 // 结果 2 { 3 '1': { id: 1, username: 'john', sex: 1, email: 'john@163.com' }, 4 '2': { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' }, 5 '3': { id: 3, username: 'nancy', sex: 0, email: '' } 6 }
我们一点一点来分析结果:
1、其实每次调用callback都return了一个对象,如上图所示。但最后只返回了一个新对象,因为每次都是在原来的对象即acc(previousValue)基础上解构的。
2、[person.id]则是属性'id',person则是id的值。
3、{}则是初始值,其实这个初始值传{}、[]都是一样的,甚至传null都可以。但是一定要传,因为不传的话,则会从数组索引为1的第二项开始。
这是不传初始值的结果:
// 不传初始值 { '2': { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' }, '3': { id: 3, username: 'nancy', sex: 0, email: '' }, id: 1, username: 'john', sex: 1, email: 'john@163.com' }