JavaScript中三種非破壞性處理數(shù)組的方法比較
在這篇文章中,我們將會(huì)探索處理數(shù)組的三種方法:
for…of
循環(huán)- 數(shù)組方法
.reduce()
- 數(shù)組方法
.flatMap()
目的是幫助你在需要處理數(shù)組的時(shí)候在這些特性之間做出選擇。如果你還不知道.reduce()
和.flatMap()
,這里將向你解釋它們。
為了更好地感受這三個(gè)特性是如何工作的,我們分別使用它們來(lái)實(shí)現(xiàn)以下功能:
- 過(guò)濾一個(gè)輸入數(shù)組以產(chǎn)生一個(gè)輸出數(shù)組
- 將每個(gè)輸入數(shù)組元素映射為一個(gè)輸出數(shù)組元素
- 將每個(gè)輸入數(shù)組元素?cái)U(kuò)展為零個(gè)或多個(gè)輸出數(shù)組元素
- 過(guò)濾-映射(過(guò)濾和映射在一個(gè)步驟中)
- 計(jì)算一個(gè)數(shù)組的摘要
- 查找一個(gè)數(shù)組元素
- 檢查所有數(shù)組元素的條件
我們所做的一切都是非破壞性的:輸入的數(shù)組永遠(yuǎn)不會(huì)被改變。如果輸出是一個(gè)數(shù)組,它永遠(yuǎn)是新建的。
for-of循環(huán)
下面是數(shù)組如何通過(guò)for-of
進(jìn)行非破壞性的轉(zhuǎn)換:
首先聲明變量result
,并用一個(gè)空數(shù)組初始化它。
對(duì)于輸入數(shù)組的每個(gè)元素elem
:
如果一個(gè)值應(yīng)該被添加到result
中:
對(duì)elem
進(jìn)行必要的轉(zhuǎn)換并將其推入result
。
使用for-of過(guò)濾
讓我們來(lái)感受一下通過(guò)for-of
處理數(shù)組,并實(shí)現(xiàn)(簡(jiǎn)易版的)數(shù)組方法.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
來(lái)實(shí)現(xiàn)數(shù)組方法.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擴(kuò)展
collectFruits()
返回?cái)?shù)組中所有人的所有水果:
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過(guò)濾&映射
下列代碼在一步中進(jìn)行過(guò)濾以及映射:
/** * 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'] );
- 過(guò)濾是通過(guò)A行的
if
語(yǔ)句和B行的.push()
方法完成的。 - 映射是通過(guò)推送
movie.title
(而不是元素movie
)完成的。
使用for-of計(jì)算摘要
getAverageGrade()
計(jì)算了學(xué)生數(shù)組的平均等級(jí):
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 );
注意事項(xiàng):用小數(shù)點(diǎn)后的分?jǐn)?shù)計(jì)算可能會(huì)導(dǎo)致四舍五入的錯(cuò)誤。
使用for-of查找
for-of
也擅長(zhǎng)在未排序的數(shù)組中查找元素:
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 );
這里,一旦我們找到了什么,我們就可以通過(guò)return
來(lái)提前離開循環(huán)(A行)。
使用for-of檢查條件
當(dāng)實(shí)現(xiàn)數(shù)組方法.every()
時(shí),我們?cè)俅螐奶崆敖K止循環(huán)中獲益(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 );
何時(shí)使用
在處理數(shù)組時(shí),for-of
是一個(gè)非常常用的工具:
- 通過(guò)推送創(chuàng)建輸出數(shù)組很容易理解。
- 當(dāng)結(jié)果不是數(shù)組時(shí),我們可以通過(guò)
return
或break
來(lái)提前結(jié)束循環(huán),這通常很有用。
for-of
的其他好處包括:
- 它可以與同步迭代一起工作。而且我們可以通過(guò)切換到
for-await-of
循環(huán)來(lái)支持異步迭代。 - 我們可以在允許使用
await
和yield
操作的函數(shù)中使用它們。
for-of
的缺點(diǎn)是,它可能比其他方法更冗長(zhǎng)。這取決于我們?cè)噲D解決什么問題。
生成器和for-of
上一節(jié)已經(jīng)提到了yield
,但我還想指出,生成器對(duì)于處理和生產(chǎn)同步和異步迭代來(lái)說(shuō)是多么的方便。
舉例來(lái)說(shuō),下面通過(guò)同步生成器來(lái)實(shí)現(xiàn).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'] );
數(shù)組方法.reduce()
數(shù)組方法.reduce()
讓我們計(jì)算數(shù)組的摘要。它是基于以下算法的:
[初始化摘要] 我們用一個(gè)適用于空數(shù)組的值初始化摘要。
我們?cè)跀?shù)組上循環(huán)。每個(gè)數(shù)組元素:
[更新摘要] 我們通過(guò)將舊的摘要與當(dāng)前元素結(jié)合起來(lái)計(jì)算一個(gè)新的摘要。
在我們了解.reduce()
之前,讓我們通過(guò)for-of
來(lái)實(shí)現(xiàn)它的算法。我們將用串聯(lián)一個(gè)字符串?dāng)?shù)組作為一個(gè)例子:
function concatElements(arr) { let summary = ''; // initializing for (const element of arr) { summary = summary + element; // updating } return summary; } assert.equal( concatElements(['a', 'b', 'c']), 'abc' );
數(shù)組方法.reduce()
循環(huán)數(shù)組,并持續(xù)為我們跟蹤數(shù)組的摘要,因此可以聚焦于初始化和更新值。它使用"累加器"這一名稱作為"摘要"的粗略同義詞。.reduce()
有兩個(gè)參數(shù):
回調(diào):
輸入:舊的累加器和當(dāng)前元素
輸出:新的累加器
累加器的初始值。
在下面代碼中,我們使用.reduce()
來(lái)實(shí)現(xiàn)concatElements()
:
const concatElements = (arr) => arr.reduce( (accumulator, element) => accumulator + element, // updating '' // initializing );
使用.reduce()過(guò)濾
.reduce()
是相當(dāng)通用的。讓我們用它來(lái)實(shí)現(xiàn)過(guò)濾:
const filterArray = (arr, callback) => arr.reduce( (acc, elem) => callback(elem) ? [...acc, elem] : acc, [] ); assert.deepEqual( filterArray(['', 'a', '', 'b'], str => str.length > 0), ['a', 'b'] );
不過(guò),當(dāng)涉及到以非破壞性的方式向數(shù)組添加元素時(shí),JavaScript 數(shù)組的效率并不高(與許多函數(shù)式編程語(yǔ)言中的鏈接列表相比)。因此,突變累加器的效率更高:
const filterArray = (arr, callback) => arr.reduce( (acc, elem) => { if (callback(elem)) { acc.push(elem); } return acc; }, [] );
使用.reduce()映射
我們可以通過(guò).reduce()
來(lái)實(shí)現(xiàn)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()擴(kuò)展
使用.reduce()
進(jìn)行擴(kuò)展:
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()過(guò)濾&映射
使用.reduce()
在一步中進(jìn)行過(guò)濾和映射:
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()計(jì)算摘要
如果我們能在不改變累加器的情況下有效地計(jì)算出一個(gè)摘要,那么.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()
實(shí)現(xiàn)的簡(jiǎn)易版的數(shù)組方法.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()
有一個(gè)限制:一旦我們找到一個(gè)值,我們?nèi)匀灰L問其余的元素,因?yàn)槲覀儾荒芴崆巴顺?。不過(guò)for-of
沒有這個(gè)限制。
使用.reduce()檢查條件
下面是使用.reduce()
實(shí)現(xiàn)的簡(jiǎn)易版的數(shù)組方法.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()
中退出,這個(gè)實(shí)現(xiàn)會(huì)更有效率。
何時(shí)使用
.reduce()
的一個(gè)優(yōu)點(diǎn)是簡(jiǎn)潔。缺點(diǎn)是它可能難以理解--特別是如果你不習(xí)慣于函數(shù)式編程的話。
以下情況我會(huì)使用.reduce()
:
1.我不需要對(duì)累加器進(jìn)行變異。
2.我不需要提前退出。
3.我不需要對(duì)同步或異步迭代器的支持。
然而,為迭代器實(shí)現(xiàn)reduce
是相對(duì)容易的。
只要能在不突變的情況下計(jì)算出一個(gè)摘要(比如所有元素的總和),.reduce()
就是一個(gè)好工具。
不過(guò),JavaScript并不擅長(zhǎng)以非破壞性的方式增量創(chuàng)建數(shù)組。這就是為什么我在JavaScript中較少使用.reduce()
,而在那些有內(nèi)置不可變列表的語(yǔ)言中則較少使用相應(yīng)的操作。
數(shù)組方法.flatMap()
普通的.map()
方法將每個(gè)輸入元素精確地翻譯成一個(gè)輸出元素。
相比之下,.flatMap()
可以將每個(gè)輸入元素翻譯成零個(gè)或多個(gè)輸出元素。為了達(dá)到這個(gè)目的,回調(diào)并不返回值,而是返回值的數(shù)組。它等價(jià)于在調(diào)用 map()
方法后再調(diào)用深度為 1 的 flat()
方法(arr.map(...args).flat()
),但比分別調(diào)用這兩個(gè)方法稍微更高效一些。
assert.equal( [0, 1, 2, 3].flatMap(num => new Array(num).fill(String(num))), ['1', '2', '2', '3', '3', '3'] );
使用.flatMap()過(guò)濾
下面展示如何使用.flatMap()
進(jìn)行過(guò)濾:
const filterArray = (arr, callback) => arr.flatMap( elem => callback(elem) ? [elem] : [] ); assert.deepEqual( filterArray(['', 'a', '', 'b'], str => str.length > 0), ['a', 'b'] );
使用.flatMap()映射
下面展示如何使用.flatMap()
進(jìn)行映射:
const mapArray = (arr, callback) => arr.flatMap( elem => [callback(elem)] ); assert.deepEqual( mapArray(['a', 'b', 'c'], str => str + str), ['aa', 'bb', 'cc'] );
使用.flatMap()過(guò)濾&映射
一步到位的過(guò)濾和映射是.flatMap()
的優(yōu)勢(shì)之一:
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()擴(kuò)展
將輸入元素?cái)U(kuò)展為零或更多的輸出元素是.flatMap()
的另一個(gè)優(yōu)勢(shì):
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()只能產(chǎn)生數(shù)組
使用.flatMap()
,我們只能產(chǎn)生數(shù)組。這使得我們無(wú)法:
- 用
.flatMap()
計(jì)算摘要 - 用
.flatMap()
查找 - 用
.flatMap()
檢查條件
我們可以產(chǎn)生一個(gè)被數(shù)組包裹的值。然而,我們不能在回調(diào)的調(diào)用之間傳遞數(shù)據(jù)。而且我們不能提前退出。
何時(shí)使用
.flatMap()
擅長(zhǎng):
- 同時(shí)進(jìn)行過(guò)濾和映射
- 將輸入元素?cái)U(kuò)展為零或多個(gè)輸出元素
我還發(fā)現(xiàn)它相對(duì)容易理解。然而,它不像for-of
和.reduce()
那樣用途廣泛:
- 它只能產(chǎn)生數(shù)組作為結(jié)果。
- 我們不能在回調(diào)的調(diào)用之間傳遞數(shù)據(jù)。
- 我們不能提前退出。
建議
那么,我們?nèi)绾巫罴训厥褂眠@些工具來(lái)處理數(shù)組呢?我大致的建議是:
1.使用你所擁有的最具體的工具來(lái)完成這個(gè)任務(wù):
- 你需要過(guò)濾嗎?請(qǐng)使用
.filter()
。 - 你需要映射嗎?請(qǐng)使用
.map()
。 - 你需要檢查元素的條件嗎?使用
.some()
或.every()
。 - 等等。
2.for-of
是最通用的工具。根據(jù)我的經(jīng)驗(yàn):
- 熟悉函數(shù)式編程的人,傾向于使用
.reduce()
和.flatMap()
。 - 不熟悉函數(shù)式編程的人通常認(rèn)為
for-of
更容易理解。然而,for-of
通常會(huì)導(dǎo)致更多冗長(zhǎng)的代碼。
3.如果不需要改變累加器,.reduce()
擅長(zhǎng)計(jì)算摘要(如所有元素的總和)。
4..flatMap()
擅長(zhǎng)于過(guò)濾&映射和將輸入元素?cái)U(kuò)展為零或更多的輸出元素。
以上就是JavaScript中三種非破壞性處理數(shù)組的方法比較的詳細(xì)內(nèi)容,更多關(guān)于JavaScript處理數(shù)組的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
js指定步長(zhǎng)實(shí)現(xiàn)單方向勻速運(yùn)動(dòng)
這篇文章主要為大家詳細(xì)介紹了js指定步長(zhǎng)實(shí)現(xiàn)單方向勻速運(yùn)動(dòng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07javascript使用shift+click實(shí)現(xiàn)選擇和反選checkbox的方法
這篇文章主要介紹了javascript使用shift+click實(shí)現(xiàn)選擇和反選checkbox的方法,涉及javascript針對(duì)鍵盤按鍵的判斷及checkbox的操作技巧,需要的朋友可以參考下2015-05-05JS控制只能輸入數(shù)字并且最多允許小數(shù)點(diǎn)兩位
這篇文章主要介紹了JS控制只能輸入數(shù)字并且最多允許小數(shù)點(diǎn)兩位,本文給大家提到j(luò)s如何限制input輸入框只能輸入數(shù)字問題,需要的朋友可以參考下2019-11-11javascript 3d 逐偵產(chǎn)品展示(核心精簡(jiǎn))
這篇文章主要介紹了javascript實(shí)現(xiàn)的3d逐偵產(chǎn)品展示,需要的朋友可以參考下2014-03-03網(wǎng)站內(nèi)容禁止復(fù)制和粘貼、另存為的js代碼
這篇文章主要介紹了JS如何實(shí)現(xiàn)網(wǎng)站內(nèi)容如何實(shí)現(xiàn)禁止復(fù)制和粘貼、另存為,需要的朋友可以參考下2014-02-02