JS数组Reduce方法功能与用法实例详解(2)

const array = [[0, [111, 222], 1], [2, [333, [444, 555]], 3], [4, 5]] const flatten = arr => { return arr.reduce((a, b) => { if (b instanceof Array) { return a.concat(flatten(b)) } return a.concat(b) }, []) } console.log(flatten(array)); // [0, 111, 222, 1, 2, 333, 444, 555, 3, 4, 5]

统计字符串中每个字符出现的次数

每次回调执行的时候,都会往对象中加一个key为字符串,value为出现次数的键值,若已经存储过字符串,那么它的value加1。

const str = 'adefrfdnnfhdueassjfkdiskcddfjds' const arr = str.split('') const strObj = arr.reduce((all, current) => { if (current in all) { all[current]++ } else { all[current] = 1 } return all }, {}) console.log(strObj) // {"a":2,"d":7,"e":2,"f":5,"r":1,"n":2,"h":1,"u":1,"s":4,"j":2,"k":2,"i":1,"c":1}

数组去重

const arr = ['1', 'a', 'c', 'd', 'a', 'c', '1'] const afterUnique = arr.reduce((all, current) => { if (!all.includes(current)) { all.push(current) } return all }, []) console.log(afterUnique); // ["1", "a", "c", "d"]

按照顺序调用promise

这种方式实际上处理的是promise的value,将上一个promise的value作为下一个promise的value进行处理。

const prom1 = a => { return new Promise((resolve => { resolve(a) })) } const prom2 = a => { return new Promise((resolve => { resolve(a * 2) })) } const prom3 = a => { return new Promise((resolve => { resolve(a * 3) })) } const arr = [prom1, prom2, prom3] const result = arr.reduce((all, current) => { return all.then(current) }, Promise.resolve(10)) result.then(res => { console.log(res); })

实现

通过上面的用法,可以总结出来reduce的特点:

接收两个参数,第一个为函数,函数内会接收四个参数:Accumulator Current CurrentIndex SourceArray,第二个参数为初始值。

返回值为一个所有Accumulator累计执行的结果

Array.prototype.myReduce = function(fn, base) { if (this.length === 0 && !base) { throw new Error('Reduce of empty array with no initial value') } for (let i = 0; i < this.length; i++) { if (!base) { base = fn(this[i], this[i + 1], i, this) i++ } else { base = fn(base, this[i], i, this) } } return base }

感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具测试上述代码运行效果。

更多关于JavaScript相关内容可查看本站专题:《JavaScript常用函数技巧汇总》、《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》及《JavaScript数学运算用法总结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/3507fcc851175f88807665a660917fe9.html