定义和用法
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数 | 描述 |
---|
function(total,currentValue, index,arr) | 必需。用于执行每个数组元素的函数。 函数参数:
参数 | 描述 |
---|
total | 必需。初始值, 或者计算结束后的返回值。 | currentValue | 必需。当前元素 | currentIndex | 可选。当前元素的索引 | arr | 可选。当前元素所属的数组对象。 |
|
initialValue | 可选。传递给函数的初始值 |
1.reduce计算数组中每个元素出现的次数
let arr = ['A', 'B', 'T', 'B', 'A'];
let stringNum = arr.reduce((pre,cur)=>{
if(cur in pre){
pre[cur]++
}else{
pre[cur] = 1
}
return pre
},{})
console.log(stringNum); //{'A': 2, 'B': 2, 'T': 1}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)