`map`和`reduce`之间的主要区别 [英] Main difference between `map` and `reduce`

查看:89
本文介绍了`map`和`reduce`之间的主要区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了这两种方法,但我对这两种方法的使用感到很困惑。

I used both methods but I am quite confused regarding the usage of both methods.

是否有 map 可以但减少不能反过来?

Is anything that map can do but reduce can not and vice versa?

注意:我知道如何使用这两种方法我是质疑这些方法与我们何时需要使用的主要区别。

Note: I know how to use both methods I am questioning for main difference between these method and when we need to used.

推荐答案



来源

两个地图 reduce 将数组和您定义的函数作为输入。它们在某种程度上是互补的: map 不能为多个元素的数组返回一个元素,而 reduce 将始终返回最终更改的累加器。

Both map and reduce have as input the array and a function you define. They are in some way complementary: map cannot return one single element for an array of multiple elements, while reduce will always return the accumulator you eventually changed.

使用 map 迭代元素,并为每个元素返回一个你想要的元素。

Using map you iterate the elements, and for each element you return an element you want.

例如,如果你有一组数字并希望获得他们的方格,你可以这样做:

For example, if you have an array of numbers and want to get their squares, you can do this:

// 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))

使用数组作为输入,您可以根据获取累加器的回调函数(第一个参数)获取一个单独的元素(比如一个Object,或一个数字,或另一个数组) / code>和 current_element 参数:

Using an array as an input, you can get one single element (let's say an Object, or a Number, or another Array) based on the callback function (the first argument) which gets the accumulator and current_element parameters:

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 计算正方形数组:

Which one should you choose when you can do the same thing with both? Try to imagine how the code looks. For the example provided, you can compute the squares array like you mentioned, using 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 来做,但简而言之,想想哪个会更短,最终会更好。

Now, looking at these, obviously the second implementation looks better and it's shorter. Usually you'd choose the cleaner solution, which in this case is map. Of course, you can do it with reduce, but in a nutshell, think which would be shorter and eventually that would be better.

这篇关于`map`和`reduce`之间的主要区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆