```svelte {#each expression as name}...{/each} ``` ```svelte {#each expression as name, index}...{/each} ``` Iterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a `length` property), or iterables like `Map` and `Set`. (Internally, they are converted to arrays with [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from).) If the value is `null` or `undefined`, it is treated the same as an empty array (which will cause [else blocks](#Else-blocks) to be rendered, where applicable). ```svelte

Shopping list

``` each ブロックは _インデックス_ も指定可能で、これは `array.map(...)` コールバックの第二引数に相当します: ```svelte {#each items as item, i}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` ## Keyed each blocks ```svelte {#each expression as name (key)}...{/each} ``` ```svelte {#each expression as name, index (key)}...{/each} ``` _key_ の式(各リストアイテムを一意に識別できる必要があります)が与えられた場合、Svelte は、データがアイテムの挿入・移動・削除によって変化したとき、リストの末尾にアイテムを追加・削除して途中のアイテムを更新するのではなく、その key を使用して賢くリストを更新します。 key はどんなオブジェクトでもよいですが、そのオブジェクト自体が変更されたときに同一性を維持できるため、文字列か数値を推奨します。 ```svelte {#each items as item (item.id)}
  • {item.name} x {item.qty}
  • {/each} {#each items as item, i (item.id)}
  • {i + 1}: {item.name} x {item.qty}
  • {/each} ``` each ブロック内では分割代入や残余構文のパターンを自由に使用できます。 ```svelte {#each items as { id, name, qty }, i (id)}
  • {i + 1}: {name} x {qty}
  • {/each} {#each objects as { id, ...rest }}
  • {id}
  • {/each} {#each items as [id, ...rest]}
  • {id}
  • {/each} ``` ## Each blocks without an item ```svelte {#each expression}...{/each} ``` ```svelte {#each expression, index}...{/each} ``` In case you just want to render something `n` times, you can omit the `as` part: ```svelte
    {#each { length: 8 }, rank} {#each { length: 8 }, file}
    {/each} {/each}
    ``` ## Else blocks ```svelte {#each expression as name}...{:else}...{/each} ``` each ブロックは `{:else}` 節を持つことができ、リストが空の場合にそれがレンダリングされます。 ```svelte {#each todos as todo}

    {todo.text}

    {:else}

    No tasks today!

    {/each} ```