做者:Axel Rauschmayer翻譯:瘋狂的技術宅javascript
本文比較並總結遍歷數組的四種方式:前端
for
循環:for (let index=0; index < someArray.length; index++) { const elem = someArray[index]; // ··· }
for-in
循環:for (const key in someArray) { console.log(key); }
.forEach()
:someArray.forEach((elem, index) => { console.log(elem, index); });
for-of
循環:for (const elem of someArray) { console.log(elem); }
for-of
一般是最佳選擇。咱們會明白緣由。java
for
循環 [ES1]JavaScript 中的 for
循環很古老,它在 ECMAScript 1 中就已經存在了。for
循環記錄 arr
每一個元素的索引和值:程序員
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); } // Output: // 0, 'a' // 1, 'b' // 2, 'c'
for
循環的優缺點是什麼?面試
for-in
循環 [ES1]for-in
循環與 for
循環同樣古老,一樣在 ECMAScript 1中就存在了。下面的代碼用 for-in
循環輸出 arr 的 key:segmentfault
const arr = ['a', 'b', 'c']; arr.prop = 'property value'; for (const key in arr) { console.log(key); } // Output: // '0' // '1' // '2' // 'prop'
for-in
不是循環遍歷數組的好方法:數組
for-in
訪問繼承屬性的實際用途是:遍歷對象的全部可枚舉屬性。服務器
.forEach()
[ES5]鑑於 for
和 for-in
都不特別適合在數組上循環,所以在 ECMAScript 5 中引入了一個輔助方法:Array.prototype.forEach()
:微信
const arr = ['a', 'b', 'c']; arr.prop = 'property value'; arr.forEach((elem, index) => { console.log(elem, index); }); // Output: // 'a', 0 // 'b', 1 // 'c', 2
這種方法確實很方便:它使咱們無需執行大量操做就可以可訪問數組元素和索引。若是用箭頭函數(在ES6中引入)的話,在語法上會更加優雅。
.forEach()
的主要缺點是:
await
。.forEach()
循環。而在 for
循環中可使用 break
。.forEach()
的解決方法若是想要停止 .forEach()
之類的循環,有一種解決方法:.some()
還會循環遍歷全部數組元素,並在其回調返回真值時中止。
const arr = ['red', 'green', 'blue']; arr.some((elem, index) => { if (index >= 2) { return true; // 停止循環 } console.log(elem); //此回調隱式返回 `undefined`,這 //是一個僞值。 所以,循環繼續。 }); // Output: // 'red' // 'green'
能夠說這是對 .some()
的濫用,與 for-of
和 break
比起來,要理解這段代碼並不容易。
for-of
循環 [ES6]for-of
循環在 ECMAScript 6 開始支持:
const arr = ['a', 'b', 'c']; arr.prop = 'property value'; for (const elem of arr) { console.log(elem); } // Output: // 'a' // 'b' // 'c'
for-of
在循環遍歷數組時很是有效:
可使用 await
for-await-of
。break
和 continue
用於外部做用域。for-of
和可迭代對象for-of
不只能夠遍歷數組,還能夠遍歷可迭代對象,例如遍歷 Map:
const myMap = new Map() .set(false, 'no') .set(true, 'yes') ; for (const [key, value] of myMap) { console.log(key, value); } // Output: // false, 'no' // true, 'yes'
遍歷 myMap
會生成 [鍵,值] 對,能夠經過對其進行解構來直接訪問每一對數據。
for-of
和數組索引數組方法 .entries()
返回一個可迭代的 [index,value]
對。若是使用 for-of
並使用此方法進行解構,能夠很方便地訪問數組索引:
const arr = ['chocolate', 'vanilla', 'strawberry']; for (const [index, elem] of arr.entries()) { console.log(index, elem); } // Output: // 0, 'chocolate' // 1, 'vanilla' // 2, 'strawberry'
for-of
循環的的可用性比 for
,for-in
和 .forEach()
更好。
一般四種循環機制之間的性能差別應該是可有可無。若是你要作一些運算量很大的事,仍是切換到 WebAssembly 更好一些。