javascript - map和reduce的主要区别

标签 javascript dictionary reduce

这两种方法我都用过,但我对这两种方法的用法很困惑。

有什么是 map 可以做而 reduce 不能做的,反之亦然?

注意:我知道如何使用这两种方法,我想知道这些方法之间的主要区别以及我们何时需要使用。

最佳答案

Source

mapreduce 都将数组和您定义的函数作为输入。它们在某种程度上是互补的: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/

相关文章:

javascript - 尝试检测数组中的三个数字是否连续出现

javascript - 可以从脚本中禁用 Firefox JavaScript JIT 吗?

python - 将值从一个键转移到python字典中的另一个键

python - 比较分配给两个字典中一个键的多个值

ios - 低质量 iOS 屏幕截图

ruby - 要求深入了解减少 ruby 代码

javascript - 与 Hogan 一起迁移到 Typeahead 0.10+

javascript - 有没有办法强制 amChart 中的最大值小于最大数据值?

c++ - 为什么 vector::operator[] 的实现方式与 map::operator[] 不同?

python - PySpark 的 reduceByKey 未按预期工作