> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/web/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/web/js/val/builtin/arr/iterate.md).

# iterating elements

[JS](/web/js.md) ⟩ [object](/web/js/val/obj.md) ⟩ [built-in](/web/js/val/builtin.md) ⟩ [Array](/web/js/val/builtin/arr.md) ⟩ iterating arrays

{% hint style="success" %}

```javascript
// ⭐️ for-of: treats "holes" as undefined
for (const value of array) {}
for (const [index, value] of array.entries()) {}    // with index

// ⭐️ forEach: ignores "holes"
arr.forEach(value => ...)        // .forEach() method
```

{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="warning" %} <mark style="color:red;">**Unlike**</mark> the [**for-of**](/web/js/grammar/statement/loop/for/of.md) loop, [**forEach()**](/web/js/grammar/statement/loop/for/foreach.md) <mark style="color:yellow;">**is aware of**</mark> [**sparse arrays**](/web/js/val/builtin/arr/sparse.md) and <mark style="color:yellow;">**does**</mark>**&#x20;**<mark style="color:red;">**not**</mark>**&#x20;**<mark style="color:yellow;">**invoke**</mark> the function for <mark style="color:orange;">**nonexistent**</mark> <mark style="color:yellow;">**elements**</mark>.
{% endhint %}
{% endtab %}

{% tab title="🔴 主題" %}

* <mark style="color:yellow;">**iterating arrays**</mark>
  * [for-of](/web/js/grammar/statement/loop/for/of.md) loop
  * [arr.forEach()](/web/js/grammar/statement/loop/for/foreach.md) method
  * [for-of vs. forEach](/web/js/grammar/statement/loop/for/of/vs-foreach.md)
    {% endtab %}

{% tab title="👥 相關" %}

* :point\_right: [for-of vs. forEach](/web/js/grammar/statement/loop/for/of/vs-foreach.md).
  {% endtab %}

{% tab title="💈範例" %}

```javascript
let a = [];        // sparse array
a[1] = 'hi';
a[5] = 'world';

let forofCount = 0;
let foreachCount = 0;

// ⭐️ for-of: treats "holes" as `undefined`.
for (const value of a) {
    forofCount += 1;
    console.log(forofCount, value);
}
// 1 undefined, 2 'hi', 3 undefined, ... 6 'world'

// ⭐️ forEach: ignores "holes".
a.forEach(value => {
    foreachCount += 1;
    console.log(foreachCount, value);
})
// 1 'hi', 2 'world'
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] JS.info ⟩ [iterables](https://javascript.info/iterable)
* [ ] [JavaScript: The Definitive Guide](/web/master/ref/javascript-the-definitive-guide.md) ⟩ 7.6 Iterating Arrays
  {% endtab %}

{% tab title="📘 手冊" %}
\*
{% endtab %}
{% endtabs %}
