#一、由map、filter、reduce、find展开
filter
filter方法可以筛除数组和类似结构中不满足条件的元素,并返回满足条件的元素组成的数组。
const integers = [1, 2, 3, 4, 6, 7];
const evenIntegers = integers.filter(i => i%2 === 0);
// evenIntegers的值为[2, 4, 6]
find
find返回数组或类似结构中满足条件的第一个元素
const posts = [
{id: 1, title: 'Title 1'},
{id: 2, title: 'Title 2'}
];
// 找出id为1的posts
const title = posts.find(p => p.id === 1).title;
map
map方法的作用在于处理流式数据,比如数组。我们可以把它想象成所有元素都要经过的一个转换器。
const integers = [1, 2, 3, 4, 6, 7];
const twoXIntegers = integers.map(i => i*2);
// twoXIntegers现在是 [2, 4, 6, 8, 12, 14],而integers不发生变化。
reduce
当你想要将多个数据放进一个实例中时,你可以使用一个reducer
const posts = [
{id: 1, upVotes: 2},
{id: 2, upVotes: 89},
{id: 3, upVotes: 1}
];
const totalUpvotes = posts.reduce((totalUpvotes, currentPost) =>
totalUpvotes + currentPost.upVotes, //reducer函数
0 // 初始化投票数为0
);
console.log(totalUpvotes)//输出投票总数:92
- 传给
reduce
的第一个参数函数还可以增加2个参数: - 第三个参数:每个元素在原数据结构中的位置,比如数组下标。
- 第四个参数:调用reduce方法的数据集合,比如例子中的posts