Loops are generally used, in any programming language, to perform operations on arrays: given an array you can iterate over its elements and perform a calculation.
循环通常以任何编程语言用于对数组执行操作:给定数组,您可以遍历其元素并执行计算。
Let’s see how to pick common needs and perform them using a Functional Programming approach, as opposed to using loops.
让我们看看如何选择常见需求并使用功能性编程方法 (而不是使用循环)执行它们。
NOTE: I don’t recommend one approach over the other. I just want to introduce different ways to perform the same thing and maybe introduce you to new functions which you might have never used until now.
注意:我不建议一种方法替代另一种方法。 我只想介绍执行同一件事的不同方法,也许还向您介绍迄今为止可能从未使用过的新功能。
map
, filter
, reduce
, find
(map
, filter
, reduce
, find
)
Those are 3 really powerful array functions:
这些是3个真正强大的数组函数:
map
returns an array with the same length,map
返回具有相同长度的数组,filter
as the name implies, it returns an array with less items than the original arrayfilter
,顾名思义,它返回的数组比原始数组少reduce
returns a single value (or object)reduce
返回单个值(或对象)find
returns the first items in an array that satisfies a conditionfind
返回满足条件的数组中的第一项
map
, filter
and reduce
were introduced in ES5, so you can safely use them as implemented in every browser since years.
map
, filter
和reduce
在ES5中引入,因此多年来您可以安全地在每种浏览器中使用它们。
find
was introduced in ES6/ES2015.
find
在ES6 / ES2015介绍。
They offer a more declarative approach, rather than an imperative approach (describe what should happen, not write every tiny bit of processing that should happen)
他们提供了一个更声明的方式 ,而不是命令式的方法(描述应该发生什么 ,不写处理是应该发生的每一个点点)
使用map
在每个元素上执行一些操作 (Execute something on every element with map
)
A loop would look like this:
循环如下所示:
const performSomething = (item) => {
//...
return item
}
const items = ['a', 'b', 'c']
items.forEach((item) => {
performSomething(item)
})
With a declarative approach, you tell JavaScript to perform something on every element using:
通过声明性方法,您可以告诉JavaScript在每个元素上执行以下操作:
const items = ['a', 'b', 'c']
const newArray = items.map((item) => performSomething(item))
This generates a new array, without editing the original one (what we call immutability)
这将生成一个新数组,而无需编辑原始数组(我们称之为不变性)
Since we use a single function in the map callback function, we can rewrite the sample as:
由于我们在地图回调函数中使用单个函数,因此可以将示例重写为:
const items = ['a', 'b', 'c']
const newArray = items.map(performSomething)
在数组中查找单个元素 (Finding a single element in the array)
Sometimes you need to look for a specific item in the array, and return it.
有时您需要在数组中查找特定项目,然后将其返回。
This is how you would do so with a loop:
这是循环执行的方式:
const items = [
{ name: 'a', content: { /* ... */ }},
{ name: 'b', content: { /* ... */ }},
{ name: 'c', content: { /* ... */ }}
]
for (const item of items) {
if (item.name === 'b') {
return item
}
}
Here is the non-loop version, using find()
(ES6+):
这是使用find()
(ES6 +)的非循环版本:
const b = items.find((item) => item.name === 'b')
Here is the same functionality using filter()
(ES5+):
这是使用filter()
(ES5 +)的相同功能:
const b = items.filter((item) => item.name === 'b').shift()
shift() returns the first item in the array without raising an error if the array is empty (returns
undefined
in that case).如果数组为空,则shift()返回数组中的第一项,而不会引发错误(在这种情况下,返回
undefined
)。
Note: shift()
mutates the array, but the array it mutates is the one returned by filter()
, not the original array. If this sounds unacceptable, you can check if the array is not empty and get the first item using b[0]
.
注意: shift()
改变数组,但它会改变的数组是filter()
返回的数组,而不是原始数组。 如果这听起来不可接受,则可以检查数组是否不为空,并使用b[0]
获取第一项。
For learning purposes (does not make much sense in practice), here is the same functionality using reduce()
:
出于学习目的(在实践中没有多大意义),这是使用reduce()
的相同功能:
const items = [
{ name: 'a', content: { /* ... */ }},
{ name: 'b', content: { /* ... */ }},
{ name: 'c', content: { /* ... */ }}
]
const b = items.reduce((result, item) => {
if (item.name === 'b') { result = item }
return result
}, null)
filter()
and reduce()
will iterate over all the array items, while find()
will be faster.
filter()
和reduce()
将遍历所有数组项,而find()
将更快。
遍历数组以计算每个项目的属性 (Iterate over an array to count a property of each item)
Use reduce()
to get a single value out of an array. For example sum the items content.value
property:
使用reduce()
从数组中获取单个值。 例如,对项目的content.value
属性求和:
const items = [
{ name: 'a', content: { value: 1 }},
{ name: 'b', content: { value: 2 }},
{ name: 'c', content: { value: 3 }}
]
using a loop:
使用循环:
let count = 0
for (const item of items) {
count += item.content.value
}
can written as
可以写成
const count = items.reduce((result, { content: { value } }) => result + value, 0)
翻译自: https://flaviocopes.com/javascript-loops-map-filter-reduce-find/