js中reduce用法

reduce() 方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:初始值(上一次回调的返回值),当前元素值,当前索引,原数组 

语法:arr.reduce(callback,[initialValue])

callback:函数中包含四个参数

- previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
- currentValue (数组中当前被处理的元素)
- index (当前元素在数组中的索引)
- array (调用的数组)
 
initialValue (作为第一次调用 callback 的第一个参数。)
var arr = [0,1,2,3,4];

arr.reduce(function(val,item,index,thisArr){
    // val == 上一次循环的值
    // item == 当前循环对应的数组值
    // index == 当前循环对应的索引值
    // 当前被循环的原数组

    // 会有一个return ,返回值会成为下一次循环的val值
    return val
},0)

  

 

利用reduce来计算一个字符串中每个字母出现次数

1 const str = 'jshdjsihh';
2     const obj = str.split('').reduce((pre,item) => {
3         pre[item] ? pre[item] ++ : pre[item] = 1
4         return pre
5     },{})
6 console.log(obj) // {j: 2, s: 2, h: 3, d: 1, i: 1}
posted @ 2022-02-24 23:44  月光怀古  阅读(319)  评论(0)    收藏  举报