关于reduce:由浅入深讲解数组的reduce用法

数组中的reduce犹如一只魔法棒,通过它能够做一些黑科技一样的事件。本文从api解说到个别用法再到高级用法,由浅入深的讲一讲数组中的reduce。MDN链接 Array.prototype.reducereduce的api是这样的, reduce(callback(accumulator, currentValue[, index, array])[,initialValue])Callback accumulator 积攒的值currentValue 以后值index 以后下标array 以后数组initialValue 初始值reduce承受两个参数,回调函数和初识值,初始值是可选的。回调函数承受4个参数:积攒值、以后值、以后下标、以后数组。如果reduce的参数只有一个,那么积攒值一开始是数组中第一个值,如果reduce的参数有两个,那么积攒值一开始是出入的initialValue初始值。而后在每一次迭代时,返回的值作为下一次迭代的accumulator 积攒值。 重要阐明:如果未设置initialValue,那么reduce将应用您的第一个数组值作为第一次迭代的accumulator,从第二个数组元素上开始循环,从index=1开始(如果有的话) 以下是reduce的几种理论利用。 1. 将数组转化为对象将上面的数组转成以id为key的对象。 const userList = [ { id: 1, username: 'john', sex: 1, email: 'john@163.com' }, { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' }, { id: 3, username: 'nancy', sex: 0, email: '' }];let objUserList = userList.reduce(keyByUserNameReducer, {})function keyByUserNameReducer(acculumator, currentValue, currentIndex, array) { return {...acculumator, [currentValue.id]: currentValue}}console.log(objUserList)// {// '1': { id: 1, username: 'john', sex: 1, email: 'john@163.com' },// '2': { id: 2, username: 'jerry', sex: 1, email: 'jerry@163.com' },// '3': { id: 3, username: 'nancy', sex: 0, email: '' }// }2. 将小数组开展成大数组将上面数组依照逗号宰割. ...

July 26, 2020 · 2 min · jiezi