In Svelte when we run each
loop we generally do it over an array of items. So, each iteration will provide single item. But there might be situations when we wish to run the loop x amount of times without any array. For such cases we can create a temporary array and loop over it. Check this code –
<p>This will list 3 items -</p> {#each Array(3) as _, i} <p>Item {i+1}</p> {/each}
Let’s understand this code. Here we declared a temporary array with 3 items, Array(3)
. This is an uninitialized array with 3 undefined items but since we do not need these items so we don’t care about them. We just need to run the loop 3 times. To denote a single item, we are using _
. We always use this character to indicate that we are using it to fulfill the conditions but we have no intention to use them for any computation or anything.
Next we used i
after a comma. In Svelte, this indicates index and it starts from 0.
Another way of doing it is by using length
property. Check this out –
<p>This will list 5 items. Using length property -</p> {#each {length: 5} as _, i} <p>Item {i+1}</p> {/each}