本文深入比较了 JavaScript 中三种非破坏性处理数组的核心方法:for-of 循环、Array.prototype.reduce() 以及 Array.prototype.flatMap()。通过过滤、映射、扩展、摘要计算及查找等具体场景的代码实现,详细解析了各方法的算法逻辑、性能特征与适用边界。文章指出,for-of 在需要提前退出或处理异步迭代时更具优势;reduce 适用于无需突变累加器的摘要计算;而 flatMap 则是同时执行过滤与映射或展平嵌套结构的最佳选择。
本文将探讨处理数组的三种主要技术路径:
for…of循环- 数组方法
.reduce() - 数组方法
.flatMap()
旨在帮助你在处理数组时,根据具体需求在这些特性之间做出恰当选择。若你对 .reduce() 和 .flatMap() 尚不熟悉,下文将对其进行详细解释。
为了直观感受这三个特性的工作机制,我们将分别利用它们来实现以下功能:
- 过滤输入数组以生成输出数组
- 将每个输入数组元素映射为单个输出数组元素
- 将每个输入数组元素扩展为零个或多个输出数组元素
- 过滤与映射(在单一步骤中完成过滤和映射操作)
- 计算数组的摘要值
- 查找数组中的特定元素
- 检查数组中所有元素是否满足特定条件
上述所有操作均遵循非破坏性原则:输入数组始终保持不变。若输出结果为数组,它必然是新创建的实例。
for-of 循环
以下是通过 for-of 实现数组非破坏性转换的基本模式:
首先声明变量 result,并将其初始化为一个空数组。
遍历输入数组的每个元素 elem:
若某值符合添加到 result 的条件:
对 elem 执行必要的转换操作,随后将其推入 result。
使用 for-of 进行过滤
让我们通过 for-of 处理数组,并实现(简易版的)数组方法 .filter():
function filterArray(arr, callback) {
const result = [];
for (const elem of arr) {
if (callback(elem)) {
result.push(elem);
}
}
return result;
}
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
使用 for-of 进行映射
同样地,我们可以利用 for-of 来实现数组方法 .map()。
function mapArray(arr, callback) {
const result = [];
for (const elem of arr) {
result.push(callback(elem));
}
return result;
}
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
使用 for-of 进行扩展
collectFruits() 返回数组中所有人的所有水果列表:
function collectFruits(persons) {
const result = [];
for (const person of persons) {
result.push(...person.fruits);
}
return result;
}
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
使用 for-of 进行过滤与映射
以下代码在单一步骤中同时完成过滤与映射操作:
/**
* What are the titles of movies whose rating is at least `minRating`?
*/
function getTitles(movies, minRating) {
const result = [];
for (const movie of movies) {
if (movie.rating >= minRating) { // (A)
result.push(movie.title); // (B)
}
}
return result;
}
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
- 过滤操作由 A 行的
if语句和 B 行的.push()方法共同完成。 - 映射操作通过推送
movie.title(而非原始元素movie)来实现。
使用 for-of 计算摘要
getAverageGrade() 计算了学生数组的平均等级:
function getAverageGrade(students) {
let sumOfGrades = 0;
for (const student of students) {
sumOfGrades += student.grade;
}
return sumOfGrades / students.length;
}
const STUDENTS = [
{
id: 'qk4k4yif4a',
grade: 4.0,
},
{
id: 'r6vczv0ds3',
grade: 0.25,
},
{
id: '9s53dn6pbk',
grade: 1,
},
];
assert.equal(
getAverageGrade(STUDENTS),
1.75
);
注意事项:涉及小数点后分数的计算可能会引发四舍五入误差。
使用 for-of 进行查找
for-of 在未排序数组中查找元素方面表现优异:
function findInArray(arr, callback) {
for (const [index, value] of arr.entries()) {
if (callback(value)) {
return {index, value}; // (A)
}
}
return undefined;
}
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 0),
{index: 1, value: 'a'}
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 1),
undefined
);
在此场景中,一旦找到目标值,即可通过 return 提前退出循环(A 行)。
使用 for-of 检查条件
在实现数组方法 .every() 时,我们再次受益于提前终止循环的能力(A 行):
function everyArrayElement(arr, condition) {
for (const elem of arr) {
if (!condition(elem)) {
return false; // (A)
}
}
return true;
}
assert.equal(
everyArrayElement(['a', '', 'b'], str => str.length > 0),
false
);
assert.equal(
everyArrayElement(['a', 'b'], str => str.length > 0),
true
);
何时使用 for-of
在处理数组时,for-of 是一项极为常用的工具:
- 通过 push 创建输出数组的逻辑直观易懂。
- 当结果并非数组时,我们可以利用
return或break提前结束循环,这通常非常有用。
for-of 的其他优势包括:
- 它支持同步迭代。此外,通过切换至
for-await-of循环,还可以支持异步迭代。 - 我们可以在允许使用
await和yield操作的函数中调用它们。
for-of 的缺点在于,它可能比其他方法更为冗长。具体取决于所解决的问题。
生成器和 for-of
上一节已提及 yield,但我希望强调,生成器在处理同步和异步迭代的生产与消费方面极为便捷。
例如,下面通过同步生成器来实现 .filter() 和 .map():
function* filterIterable(iterable, callback) {
for (const item of iterable) {
if (callback(item)) {
yield item;
}
}
}
const iterable1 = filterIterable(
['', 'a', '', 'b'],
str => str.length > 0
);
assert.deepEqual(
Array.from(iterable1),
['a', 'b']
);
function* mapIterable(iterable, callback) {
for (const item of iterable) {
yield callback(item);
}
}
const iterable2 = mapIterable(['a', 'b', 'c'], str => str + str);
assert.deepEqual(
Array.from(iterable2),
['aa', 'bb', 'cc']
);
数组方法 .reduce()
数组方法 .reduce() 使我们能够计算数组的摘要。其基于以下算法:
[初始化摘要] 我们使用一个适用于空数组的值来初始化摘要。
我们在数组上进行循环。对于每个数组元素:
[更新摘要] 通过将旧摘要与当前元素结合,计算出新的摘要。
在了解 .reduce() 之前,让我们通过 for-of 来实现其算法。我们将以串联字符串数组为例:
function concatElements(arr) {
let summary = ''; // initializing
for (const element of arr) {
summary = summary + element; // updating
}
return summary;
}
assert.equal(
concatElements(['a', 'b', 'c']),
'abc'
);
数组方法 .reduce() 遍历数组,并持续为我们跟踪数组的摘要,因此我们可以专注于初始化和更新值的逻辑。它使用“累加器”这一名称作为“摘要”的大致同义词。.reduce() 接收两个参数:
回调函数:
输入:旧的累加器和当前元素
输出:新的累加器
累加器的初始值。
在以下代码中,我们使用 .reduce() 来实现 concatElements():
const concatElements = (arr) => arr.reduce(
(accumulator, element) => accumulator + element, // updating
'' // initializing
);
使用 .reduce() 进行过滤
.reduce() 具有相当的通用性。让我们用它来实现过滤:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => callback(elem) ? [...acc, elem] : acc,
[]
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
不过,当涉及以非破坏性方式向数组添加元素时,JavaScript 数组的效率并不理想(与许多函数式编程语言中的链接列表相比)。因此,突变累加器的效率更高:
const filterArray = (arr, callback) => arr.reduce(
(acc, elem) => {
if (callback(elem)) {
acc.push(elem);
}
return acc;
},
[]
);
使用 .reduce() 进行映射
我们可以通过 .reduce() 来实现 map:
const mapArray = (arr, callback) => arr.reduce(
(acc, elem) => [...acc, callback(elem)],
[]
);
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
以下是效率更高的突变版本:
const mapArray = (arr, callback) => arr.reduce(
(acc, elem) => {
acc.push(callback(elem));
return acc;
},
[]
);
使用 .reduce() 进行扩展
使用 .reduce() 进行扩展:
const collectFruits = (persons) => persons.reduce(
(acc, person) => [...acc, ...person.fruits],
[]
);
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
突变版本:
const collectFruits = (persons) => persons.reduce(
(acc, person) => {
acc.push(...person.fruits);
return acc;
},
[]
);
使用 .reduce() 进行过滤与映射
使用 .reduce() 在单一步骤中完成过滤和映射:
const getTitles = (movies, minRating) => movies.reduce(
(acc, movie) => (movie.rating >= minRating)
? [...acc, movie.title]
: acc,
[]
);
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
效率更高的突变版本:
const getTitles = (movies, minRating) => movies.reduce(
(acc, movie) => {
if (movie.rating >= minRating) {
acc.push(movie.title);
}
return acc;
},
[]
);
使用 .reduce() 计算摘要
如果我们能在不改变累加器的情况下有效地计算出摘要,那么 .reduce() 就非常出色:
const getAverageGrade = (students) => {
const sumOfGrades = students.reduce(
(acc, student) => acc + student.grade,
0
);
return sumOfGrades / students.length;
};
const STUDENTS = [
{
id: 'qk4k4yif4a',
grade: 4.0,
},
{
id: 'r6vczv0ds3',
grade: 0.25,
},
{
id: '9s53dn6pbk',
grade: 1,
},
];
assert.equal(
getAverageGrade(STUDENTS),
1.75
);
使用 .reduce() 进行查找
以下是使用 .reduce() 实现的简易版数组方法 .find():
const findInArray = (arr, callback) => arr.reduce(
(acc, value, index) => (acc === undefined && callback(value))
? {index, value}
: acc,
undefined
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 0),
{index: 1, value: 'a'}
);
assert.deepEqual(
findInArray(['', 'a', '', 'b'], str => str.length > 1),
undefined
);
这里 .reduce() 存在一个限制:一旦找到值,我们仍需访问剩余元素,因为我们无法提前退出。不过 for-of 没有此限制。
使用 .reduce() 检查条件
以下是使用 .reduce() 实现的简易版数组方法 .every():
const everyArrayElement = (arr, condition) => arr.reduce(
(acc, elem) => !acc ? acc : condition(elem),
true
);
assert.equal(
everyArrayElement(['a', '', 'b'], str => str.length > 0),
false
);
assert.equal(
everyArrayElement(['a', 'b'], str => str.length > 0),
true
);
同样地,如果我们能提前从 .reduce() 中退出,该实现将更具效率。
何时使用 .reduce()
.reduce() 的一个优点是代码简洁。缺点是它可能难以理解——特别是对于不熟悉函数式编程的开发者而言。
在以下情况下我会使用 .reduce():
1. 我不需要对累加器进行突变。
2. 我不需要提前退出。
3. 我不需要对同步或异步迭代器的支持。
然而,为迭代器实现 reduce 相对容易。
只要能在不突变的情况下计算出摘要(例如所有元素的总和),.reduce() 就是一个好工具。
不过,JavaScript 并不擅长以非破坏性方式增量创建数组。这就是为什么我在 JavaScript 中较少使用 .reduce(),而在那些有内置不可变列表的语言中则较少使用相应的操作。
数组方法 .flatMap()
普通的 .map() 方法将每个输入元素精确地翻译成一个输出元素。
相比之下,.flatMap() 可以将每个输入元素翻译成零个或多个输出元素。为此,回调并不直接返回值,而是返回值的数组。它等价于在调用 map() 方法后再调用深度为 1 的 flat() 方法(arr.map(...args).flat()),但比分别调用这两个方法稍微更高效一些。
assert.equal(
[0, 1, 2, 3].flatMap(num => new Array(num).fill(String(num))),
['1', '2', '2', '3', '3', '3']
);
使用 .flatMap() 进行过滤
下面展示如何使用 .flatMap() 进行过滤:
const filterArray = (arr, callback) => arr.flatMap(
elem => callback(elem) ? [elem] : []
);
assert.deepEqual(
filterArray(['', 'a', '', 'b'], str => str.length > 0),
['a', 'b']
);
使用 .flatMap() 进行映射
下面展示如何使用 .flatMap() 进行映射:
const mapArray = (arr, callback) => arr.flatMap(
elem => [callback(elem)]
);
assert.deepEqual(
mapArray(['a', 'b', 'c'], str => str + str),
['aa', 'bb', 'cc']
);
使用 .flatMap() 进行过滤与映射
一步到位的过滤和映射是 .flatMap() 的优势之一:
const getTitles = (movies, minRating) => movies.flatMap(
(movie) => (movie.rating >= minRating) ? [movie.title] : []
);
const MOVIES = [
{ title: 'Inception', rating: 8.8 },
{ title: 'Arrival', rating: 7.9 },
{ title: 'Groundhog Day', rating: 8.1 },
{ title: 'Back to the Future', rating: 8.5 },
{ title: 'Being John Malkovich', rating: 7.8 },
];
assert.deepEqual(
getTitles(MOVIES, 8),
['Inception', 'Groundhog Day', 'Back to the Future']
);
使用 .flatMap() 进行扩展
将输入元素扩展为零或更多的输出元素是 .flatMap() 的另一个优势:
const collectFruits = (persons) => persons.flatMap(
person => person.fruits
);
const PERSONS = [
{
name: 'Jane',
fruits: ['strawberry', 'raspberry'],
},
{
name: 'John',
fruits: ['apple', 'banana', 'orange'],
},
{
name: 'Rex',
fruits: ['melon'],
},
];
assert.deepEqual(
collectFruits(PERSONS),
['strawberry', 'raspberry', 'apple', 'banana', 'orange', 'melon']
);
.flatMap() 只能产生数组
使用 .flatMap(),我们只能产生数组。这使得我们无法:
- 用
.flatMap()计算摘要 - 用
.flatMap()查找 - 用
.flatMap()检查条件
我们可以产生一个被数组包裹的值。然而,我们不能在回调的调用之间传递数据。而且我们不能提前退出。
何时使用 .flatMap()
.flatMap() 擅长:
- 同时进行过滤和映射
- 将输入元素扩展为零或多个输出元素
我还发现它相对容易理解。然而,它不像 for-of 和 .reduce() 那样用途广泛:
- 它只能产生数组作为结果。
- 我们不能在回调的调用之间传递数据。
- 我们不能提前退出。
建议
那么,我们如何最佳地使用这些工具来处理数组呢?我大致的建议是:
1. 使用你所拥有的最具体的工具来完成这个任务:
- 你需要过滤吗?请使用
.filter()。 - 你需要映射吗?请使用
.map()。 - 你需要检查元素的条件吗?使用
.some()或.every()。 - 等等。
2. for-of 是最通用的工具。根据我的经验:
- 熟悉函数式编程的人,倾向于使用
.reduce()和.flatMap()。 - 不熟悉函数式编程的人通常认为
for-of更容易理解。然而,for-of通常会导致更多冗长的代码。
3. 如果不需要改变累加器,.reduce() 擅长计算摘要(如所有元素的总和)。
4. .flatMap() 擅长于过滤与映射以及将输入元素扩展为零或更多的输出元素。
以上就是 JavaScript 中三种非破坏性处理数组的方法比较的详细内容,更多关于 JavaScript 处理数组的资料请关注本站其它相关文章!