转载图解
https://juejin.im/post/6844903816895152141
补充:
Map() 可以改变数组中的元素
Reduce简例:
ES5源码
/**
* Calls the specified callback function for all the elements in an array.
* The return value of the callback function is the accumulated result,
* and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments.
* The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified,
* it is used as the initial value to start the accumulation.
* The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T): T;
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
/**
* Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result,
* and is provided as an argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments.
* The reduce method calls the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation.
* The first call to the callbackfn function provides this value as an argument instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;
// 计算Christopher Nolan导演的电影的IMDB平均分
const watchList = [
{
Title: "Inception",
Director: "Christopher Nolan",
imdbRating: "8.8",
},
{
Title: "Interstellar",
Director: "Christopher Nolan",
imdbRating: "8.6",
},
{
Title: "The Dark Knight",
Director: "Christopher Nolan",
imdbRating: "9.0",
},
{
Title: "Batman Begins",
Director: "Christopher Nolan",
imdbRating: "8.3",
},
{
Title: "Avatar",
Director: "James Cameron",
imdbRating: "7.9",
},
];
let moviesCount = 0;
/**
* 回调函数calculateAverage的参数说明 传入reduce()
* @param {previousValue 必须指定 初始值 可由redece(callBackFcn(),initialValue)中的initialValue传入} sumRating
* @param {currentValue 必须 当前对象} movie
* @param {currentIndex 可选 当前对象下标} currentIndex
* @param {array 可选 当前对象所属的数组} array
*/
const calculateAverage = (sumRating, movie, currentIndex, array) => {
if (movie.Director === "Christopher Nolan") {
moviesCount += 1;
return (sumRating += parseFloat(movie.imdbRating));
}
return sumRating;
};
/**
* @param {initialValue 可选 传给回调函数的previousValue} 0
*/
const averageRating = watchList.reduce(calculateAverage, 0) / moviesCount;
// 8.675
console.log(averageRating);