前言
为啥要把es6 中 reduce 单独拿出来说呢,因为这个功能实在太骚,值得如此。
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。reduce() 方法接受四个参数:初始值(或者上一次回调函数的返回值),当前元素值,当前索引,调用 reduce() 的数组。
reduce() 的几个强大用法:
数组求和
var total = [ 0, 1, 2, 3 ].reduce(( acc, cur ) => { return acc + cur }, 0); console.log(total) // 6
二维数组转为一维数组
var array = [[1, 2], [3, 4], [5, 6]].reduce(( acc, cur ) => { return acc.concat(cur) }, []); console.log(array) // [ 0, 1, 3, 4, 5, 6 ]
计算数组中每个元素出现的次数
方法一
let names = ['tom', 'jim', 'jack', 'tom', 'jack']; const countNames = names.reduce((allNames, name) => { if (name in allNames) { allNames[name] ++; } else { allNames[name] = 1; } return allNames; }, {}); console.log(countNames) // { tom: 2, jim: 1, jack: 2 }
方法二
const arraySum = (arr, val) => arr.reduce((acc, cur) => { return cur == val "color: #ff0000">数组去重
1.方法一
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]; let result = arr.sort().reduce((init, current) => { if (init.length === 0 || init[init.length - 1] !== current) { init.push(current); } return init; }, []); console.log(result); //[1,2,3,4,5]2.方法二
当然,对于数组去重,也可以直接使用es6的…[拓展运算符] + Set 实现:
// console.log(...new Set([1,2,3,4,5,2,4,1])) const dedupe = (array) => { return Array.from(new Set(array)); } console.log(dedupe([1, 1, 2, 3])) //[1,2,3]总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
最新资源
- 【中国民乐】张维良《秋江夜泊》2004[FLAC+CUE]
- 明达年度发烧碟MasterSuperiorAudiophile2011[D
- 明达年度发烧碟MasterSuperiorAudiophile2017[D
- 翁立友.2008-恨孤单【大旗】【WAV+CUE】
- 群星.2009-Magic.Cover日粤精华3CD【环球】【WA
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][5
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量