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

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

问题描述

我同时使用了这两种方法,但是我对这两种方法的使用感到非常困惑。

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

映射的任何东西可以但 reduce 不能,反之亦然吗?

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.

推荐答案



Source

两个 map 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))

使用数组作为输入,您可以基于获取 accumulator <的回调函数(第一个参数)来获得一个单个元素(例如,对象,数字或另一个数组)。 / 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天全站免登陆