遍歷數(shù)組:for、for-in、forEach、for-of
這篇文章比較了遍歷數(shù)組的四種方式:
for 循環(huán):
- for (let index=0; index < someArray.length; index++) {
- const elem = someArray[index];
- // ···
- }
for-in 循環(huán):
- for (const key in someArray) {
- console.log(key);
- }
數(shù)組的 .forEach() 方法:
- someArray.forEach((elem, index) => {
- console.log(elem, index);
- });
for-of 循環(huán):
- for (const elem of someArray) {
- console.log(elem);
- }
for-of 往往是最好的選擇,我們會(huì)知道為什么。
for 循環(huán)[ES1]
JavaScript中的普通 for 循環(huán)已經(jīng)很老了,它在ECMAScript 1中就已經(jīng)存在了。這個(gè) `for` 循環(huán)記錄了arr的每個(gè)元素的索引和值:
- const arr = ['a', 'b', 'c'];
- arr.prop = 'property value';
- for (let index=0; index < arr.length; index++) {
- const elem = arr[index];
- console.log(index, elem);
- }
- // 輸出:
- // 0, 'a'
- // 1, 'b'
- // 2, 'c
此循環(huán)的優(yōu)缺點(diǎn)是什么?
- 它是相當(dāng)通用的,但可惜的是,當(dāng)我們要做的是在一個(gè)數(shù)組上循環(huán)時(shí),它也很啰嗦。
- 如果我們不想從第一個(gè) Array 元素開(kāi)始循環(huán),它還是很有用的。其他的循環(huán)機(jī)制都不能讓我們這樣做。
for-in 循環(huán) [ES1]
for-in 循環(huán)和 for 循環(huán)一樣古老--它在ECMAScript 1中也已經(jīng)存在。這個(gè) for-in 循環(huán)記錄了arr的鍵:
- const arr = ['a', 'b', 'c'];
- arr.prop = 'property value';
- for (const key in arr) {
- console.log(key);
- }
- // 輸出:
- // '0'
- // '1'
- // '2'
- // 'prop'
for-in 不是循環(huán)遍歷數(shù)組的好選擇:
- 它訪(fǎng)問(wèn)屬性鍵,而不是值。
- 作為屬性鍵,Array元素的索引是字符串,而不是數(shù)字
- 它訪(fǎng)問(wèn)所有可枚舉的屬性鍵(包括自有的和繼承的),而不僅僅是Array元素的屬性鍵。
for-in 訪(fǎng)問(wèn)繼承的屬性確實(shí)有一個(gè)用例:循環(huán)一個(gè)對(duì)象的所有可枚舉屬性。
Array方法.forEach() [ES5]
考慮到 for 和 for-in 都不是特別適合在Array上循環(huán),在ECMAScript 5中引入了一個(gè)輔助方法:Array.prototype.forEach()。
- const arr = ['a', 'b', 'c'];
- arr.prop = 'property value';
- arr.forEach((elem, index) => {
- console.log(elem, index);
- });
- // 輸出:
- // 'a', 0
- // 'b', 1
- // 'c', 2
這個(gè)方法真的很方便。它讓我們無(wú)需做太多事情就能訪(fǎng)問(wèn) Array 元素和 Array 元素索引。箭頭函數(shù)(在ES6中引入)使這種方法在語(yǔ)法上更加優(yōu)雅。
.forEach() 的主要缺點(diǎn)是:
- 你不能在這種循環(huán)的“主體”中使用 await。
- 你不能提早退出 .forEach() 循環(huán),在 for 循環(huán)中,我們可以使用 break。
退出.forEach()--一個(gè)變通方法
如果你想使用像 .forEach() 這樣的循環(huán)并提前離開(kāi),有一個(gè)變通的辦法:.some() 也會(huì)在所有Array元素上循環(huán),如果它的回調(diào)返回一個(gè)真值,就會(huì)停止。
- onst arr = ['red', 'green', 'blue'];
- arr.some((elem, index) => {
- if (index >= 2) {
- return true; // break from loop
- }
- console.log(elem);
- // This callback implicitly returns `undefined`, which
- // is a falsy value. Therefore, looping continues.
- });
- // 輸出:
- // 'red'
- // 'green'
可以說(shuō),這是對(duì) .some() 的濫用,我不知道這段代碼有多容易理解(與 for-of 和 break 相比)。
for-of 循環(huán) [ES6]
在ECMAScript 6中,for-of 循環(huán)被添加到JavaScript中。
- const arr = ['a', 'b', 'c'];
- arr.prop = 'property value';
- for (const elem of arr) {
- console.log(elem);
- }
- // 輸出:
- // 'a'
- // 'b'
- // 'c'
for-of 非常適合循環(huán)遍歷數(shù)組:
- 它在數(shù)組元素上進(jìn)行迭代。
- 我們可以使用 await:而且,如果需要,可以輕松遷移到 for-await-of。
- 我們可以使用 break 和 continue --即使是外部范圍。
for-of 和 iterable 對(duì)象
for-of 的另一個(gè)好處是,我們不僅可以在Arrays上循環(huán),還可以在任何可迭代對(duì)象上循環(huán)--例如,在Maps上循環(huán)。
- const myMap = new Map()
- .set(false, 'no')
- .set(true, 'yes')
- ;
- for (const [key, value] of myMap) {
- console.log(key, value);
- }
- // 輸出:
- // false, 'no'
- // true, 'yes'
在 myMap 上迭代產(chǎn)生 [key, value] 對(duì),我們對(duì)其進(jìn)行解構(gòu),以直接訪(fǎng)問(wèn)每個(gè)對(duì)的組件。
for-of 與 數(shù)組下標(biāo)
數(shù)組方法 .entries() 在 [index, value] 對(duì)上返回一個(gè)可迭代對(duì)象。如果使用 for-of 和解構(gòu)這個(gè)方法,我們可以方便地訪(fǎng)問(wèn)Array索引。
- const arr = ['chocolate', 'vanilla', 'strawberry'];
- for (const [index, elem] of arr.entries()) {
- console.log(index, elem);
- }
- // 輸出:
- // 0, 'chocolate'
- // 1, 'vanilla'
- // 2, 'strawberry'
總結(jié)
正如我們所看到的,for-of 循環(huán)比 for、for-in 和 .forEach() 的可用性要好。
四種循環(huán)機(jī)制之間的任何性能差異通常都不重要。如果有的話(huà),你可能正在做一些計(jì)算量非常大的事情,切換到WebAssembly可能是有意義的。