Source http://www.globalnerdy.com/2016/06/23/map-filter-and-reduce-explained-using-emoji/
Both map
and reduce
将数组和您定义的函数作为输入。它们在某种程度上是互补的:map
无法为包含多个元素的数组返回一个元素,而reduce
将始终返回您最终更改的累加器。
map
Using map
您迭代元素,并为每个元素返回一个所需的元素。
例如,如果您有一个数字数组并想要获取它们的平方,您可以这样做:
// A function which calculates the square
const square = x => x * x
// Use `map` to get the square of each number
console.log([1, 2, 3, 4, 5].map(square))
reduce
使用数组作为输入,您可以根据回调函数(第一个参数)获取单个元素(比如说一个对象、数字或另一个数组),该函数获取accumulator
and current_element
参数:
const numbers = [1, 2, 3, 4, 5]
// Calculate the sum
console.log(numbers.reduce(function (acc, current) {
return acc + current
}, 0)) // < Start with 0
// Calculate the product
console.log(numbers.reduce(function (acc, current) {
return acc * current
}, 1)) // < Start with 1
当您可以用两者做同样的事情时,您应该选择哪一个?尝试想象一下代码的样子。对于提供的示例,您可以像您提到的那样计算平方数组,使用reduce
:
// Using reduce
[1, 2, 3, 4, 5].reduce(function (acc, current) {
acc.push(current*current);
return acc;
}, [])
// Using map
[1, 2, 3, 4, 5].map(x => x * x)
现在,看看这些,显然第二个实现看起来更好而且更短。通常您会选择更清洁的解决方案,在本例中是map
。当然,你可以这样做reduce
,但简而言之,想想哪个会更短,最终哪个会更好。