each
block a specific x
number of times in Svelte?I know of Svelte's {#each}
block which allows you to iterate over arrays or array-likes.
<script lang="ts">
let names: string[] = ["bob", "joe", "Frankenstein"];
</script>
{#each names as name}
<span>Hello {name}!</span>
{/each}
However, there are some cases where I'm not interested in the data of an array, but rather in repeating a block a specific x
number of times. What is the idiomatic way to accomplish that in Svelte?
The Svelte documentation for {#each}
states
The values in question can be arrays, array-like objects (i.e. anything with a length property)
So to loop an each
statement a specific x
number of times you would simply provide { length: x }
as the array input.
<script lang="ts">
let x = 12;
</script>
{#each { length: x }, index}
<span>Item #{index}</span>
{/each}
Note that {#each}
without as
is only supported in Svelte 5, so in versions 4 and prior you would have to write it like so:
{#each { length: x } as _, index}
<span>Item #{index}</span>
{/each}