> 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/static-methods/fill.md).

# Array(n) vs. Array(n).fill()

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="warning" %}
**Array(3)**&#x20;

* 只會設定<mark style="color:yellow;">**陣列長度**</mark> `{length: 3}`，並<mark style="color:red;">**不會設定**</mark><mark style="color:red;">「</mark><mark style="color:red;">**整數索引**</mark><mark style="color:red;">」</mark>屬性
* 如果做 `.map()`，只會得到**空陣列**，因為 `.map()` 會保留「洞」。\
  ( 👉 下面程式第 **15** 行 )<br>

**Array(3).fill()**&#x20;

* 會填入 <mark style="color:purple;">`undefined`</mark>，並<mark style="color:yellow;">**設定**</mark><mark style="color:yellow;">「</mark><mark style="color:yellow;">**整數索引**</mark><mark style="color:yellow;">」屬性</mark>，這時使用 `.map()` 就會有實際效果。( 👉 下面程式第 **19** 行 )
  {% endhint %}
  {% endtab %}

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

```javascript
const { log } = console;

let n = 3;

// ⭐️ Array(n) does NOT set integer properties❗️
let emptyArray = Array(n);              // only set {length: n}
log(Object.keys(emptyArray));           // []

// ⭐️ Array(n).fill() DOES set integer properties❗️
let filledArray = Array(n).fill();      // {0:undefined, 1:undefined, ...}
log(Object.keys(filledArray));          // [ '0', '1', '2' ]


// ⭐ map over INTEGER properties❗️️ (⭐️ no integer to map over)
let a1 = emptyArray.map((_, i) => i);   // [ <3 empty items> ]
log(a1, a1.length);                     // ⭐️ `length` is kept by map

// ⭐ map over INTEGER properties❗
let a2 = filledArray.map((_, i) => i);  // [ 0, 1, 2 ]
log(a2);
```

{% endtab %}

{% tab title="📘 手冊" %}

* [array.fill()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#using_fill_to_populate_an_empty_array) - 沒填寫參數，表示 filled with `undefined`&#x20;
* [array.forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
* [Array()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array)
* [Array.from()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
  {% endtab %}

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

* [🌀 Array.matrixFill()](/web/js/val/builtin/arr/matrix-static-methods/fill.md) - fill a matrix.
* [sparse array](/web/js/val/builtin/arr/sparse.md) (👉 [sparse array](/web/js/val/builtin/arr/sparse.md#how-array-methods-deal-with-holes))
* [Array.list(n)](/web/js/val/builtin/arr/static-methods/array.integers.md)
  {% endtab %}

{% tab title="🗣 討論" %}

* 🗣 [Difference between Array(n) and Array(n).fill?](https://stackoverflow.com/a/35013890/5409815) ⭐️
  {% endtab %}
  {% endtabs %}
