If you get used to reduce, you can write down how to implement reduce in normal ways

Simple implementation of an array of values add

function{

const arr1 = [{num:1},{num:2},{num:3},{num:4}]; Function reduceDemo(arr,first,fn){if(typeof fn! == 'function'){console.log(' the third argument must be a function! '); return } const length = arr.length; let res = first; For (let I = 0; i < length; i++){ res = fn(res,arr[i],i,arr); } return res; Const num = reduceDemo(arr1,0,(res,arrs,index,arr2)=>{res += arrs.num; return res; }) console.log(num); // Result is 10Copy the code

}


List of topics: Juejin

theme: juejin highlight: