这两种方法我都用过,但我对这两种方法的用法很困惑。
有什么是 map
可以做而 reduce
不能做的,反之亦然?
注意:我知道如何使用这两种方法,我想知道这些方法之间的主要区别以及我们何时需要使用。
最佳答案
map
和 reduce
都将数组和您定义的函数作为输入。它们在某种程度上是互补的:map
不能为多个元素的数组返回一个元素,而 reduce
将始终返回您最终更改的累加器。
map
使用 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))
减少
使用数组作为输入,您可以根据获取累加器
和 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
来做到这一点,但简而言之,想想哪个更短,最终哪个会更好。
关于javascript - map和reduce的主要区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49934992/