JS 中循環遍歷數組方式總結

做者:Axel Rauschmayer

翻譯:瘋狂的技術宅javascript

https://2ality.com/2021/01/lo...html

本文比較並總結遍歷數組的四種方式:前端

  • 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 不是循環遍歷數組的好方法:數組

  • 它訪問的是屬性鍵,而不是值。
  • 做爲屬性鍵,數組元素的索引是字符串,而不是數字。
  • 它訪問的是全部可枚舉的屬性鍵(本身的和繼承的),而不只僅是 Array 元素的那些。

for-in 訪問繼承屬性的實際用途是:遍歷對象的全部可枚舉屬性。服務器

數組方法 .forEach() [ES5]

鑑於 forfor-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-ofbreak 比起來,要理解這段代碼並不容易。

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
  • 甚至能夠將 breakcontinue 用於外部做用域。

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 循環的的可用性比 forfor-in.forEach() 更好。

一般四種循環機制之間的性能差別應該是可有可無。若是你要作一些運算量很大的事,仍是切換到 WebAssembly 更好一些。

173382ede7319973.gif


本文首發微信公衆號:前端先鋒

歡迎掃描二維碼關注公衆號,天天都給你推送新鮮的前端技術文章

歡迎掃描二維碼關注公衆號,天天都給你推送新鮮的前端技術文章


歡迎繼續閱讀本專欄其它高贊文章:


相關文章
相關標籤/搜索