map() 方法
将一个数组作为参数,并使用对该数组中每个元素调用提供的函数的结果创建一个新的数组
const numbers = [1, 5, 10, 15];
// The associated function multiply each array number by 2
const doubles = numbers.map(x => x * 2);
console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(doubles); // [2, 10, 20, 30]
filter() 方法
提供一种针对提供的函数对数组中的每个元素进行过滤的方法,满足这个条件的元素才会添加到数组中。
const numbers = [1, 5, 10, 15];
// 添加大于等于 10 的元素
const bigOnes = numbers.filter(x => x >= 10);
console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(bigOnes); // [10, 15]
将 map() 和 filter() 一起使用
// Get titles of movies with an IMDB rating greater or equal to 7.5
const bestTitles = movies => {
/* Previous code
const bestTitles = [];
for (const movie of movies) {
if (movie.imdbRating >= 7.5) {
bestTitles.push(movie.title);
}
}
return bestTitles;
*/
// Filter movies by IMDB rating, then creates a movie titles array
return movies.filter(movie => movie.imdbRating >= 7.5).map(movie => movie.title);
};
console.log(bestTitles(movieList))
reduce() 方法
将提供的函数应用于每个数组元素,以将其减少为一个值。这个方法通常用于对数组执行计算。
const numbers = [1, 5, 10, 15];
// 计算数组元素的总和
const sum = numbers.reduce((acc, value) => acc + value, 0);
console.log(numbers); // [1, 5, 10, 15] (no change)
console.log(sum); // 31
reduece() 方法有几个参数:
- 第一个是与 reduce() 每个数组元素关联并调用的函数。它有两个参数:第一个是一个累加器,其中包含上次调用函数返回的累积值。另一个函数参数是数组元素。
- 第二个是累加器的初始值(通常为 0)