javascript / beginner
Snippet
Rendering List Indices with Array Iteration
In Svelte, the `{#each}` block allows iterating over arrays. You can access the zero-based index of each item by adding a second parameter after the comma.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
<script>let fruits = ['Apple', 'Banana', 'Orange'];</script><ul>{#each fruits as fruit, index}<li>{index + 1}: {fruit}</li>{/each}</ul>
svelte
Breakdown
1
let fruits = ['Apple', 'Banana', 'Orange'];
Defines an array of strings representing items to display.
2
{#each fruits as fruit, index}
Iterates over the `fruits` array, exposing the current item and its numerical index.
3
<li>{index + 1}: {fruit}</li>
Renders a list item displaying a 1-based index alongside the fruit name.