js篇-reduce函数

277 阅读2分钟

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

案例

1、计算数组求和

let c = [1,2,3,4,5,6,7]
let d = c.reduce((total,num) =>{
  return total + num
  // return total + Math.round(num) // 对数组元素四舍五入并计算总和
},0)
console.log(d); // 28
// num.reduce((total,num) => total _= num , 0)
// 没有初始值initialValue(即上面例子中的0),当数组为0是会抛出异常提示reduce函数没有初始值
// 所以为兼容性一般加上initialValue

2、合并二维数组

let red = [[0, 1], [2, 3], [4, 5]].reduce((a,b)=>{
  return a.concat(b)
}, []);
console.log(red) // [0,1,2,3,4,5]
  • 其实reduce函数还可以用来合并多维数组,和该写法类似,只是中间多了一个判断而已,示例如下
let a = [1,2,[3,4,5,[6,7,8],9,10]]
const demo = (a)=>{
  return a.reduce((a,b)=>{
    return a.concat(Array.isArray(b) ? demo(b) : b)
  },[])
}
console.log(demo(a)); // [1,2,3,4,5,6,7,8,9,10]

3、统计一个数组中有多少个不重复的单词

不用reduce时:

let arr = ["apple","orange","apple","orange","pear","orange"];
const getWordCnt = ()=>{
  let obj = {};
  for(let i= 0, l = arr.length; i< l; i++){
    let item = arr[i];
    obj[item] = (obj[item] +1 ) || 1;
  }
  return obj;
}
console.log(getWordCnt()); // {apple: 2, orange: 3, pear: 1}

用reduce函数时(省略了很多代码)

let arr = ["apple","orange","apple","orange","pear","orange"];
  const  getWordCnt = ()=>{
    return arr.reduce(function(prev,next){
      prev[next] = (prev[next] + 1) || 1;
      return prev;
    },{});
  }
console.log(getWordCnt()); // {apple: 2, orange: 3, pear: 1}

4、对reduce的理解:

reduce(callback,initiaValue)会传入两个变量,回调函数(callback)和初始值(initiaValue)。

假设函数有4个传入参数,prev和next,index和array。 Prev和next是你必须要了解的。

当没有传入初始值时,prev是从数组中第一个元素开始的,next数组是第二个元素。

但是当传入初始值(initiaValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素。比如:

```
let arr = ["apple","orange"];
const  noPassValue = () =>{
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    return prev;
  });
}

const passValue = () =>{
  return arr.reduce(function(prev,next){
    console.log("prev:",prev);
    console.log("next:",next);
    prev[next] = 1;
    return prev;
  },{});
}
console.log("No Additional parameter:",noPassValue());
console.log("----------------");
console.log("With {} as an additional parameter:",passValue());