Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte 3 - How to loop each block X amount of times

I'm hoping to find a way to iterate over an #each block a set amount of times in Svelte 3. In Vue I would do something like this:

<li v-for="i in 3"><!-- somecontent --></li>

But as I understand Svelte handles loops much differently using the .length property of the array being #eached. Is there some way to pull off something like this in Svelte?

{#each 3 as i}
  <li><!-- somecontent --></li>
{/if}
like image 250
JHeth Avatar asked Oct 03 '19 06:10

JHeth


People also ask

How Do You For Each loops work?

A for-each loop is a loop that can only be used on a collection of items. It will loop through the collection and each time through the loop it will use the next item from the collection. It starts with the first item in the array (the one at index 0) and continues through in order to the last item in the array.


3 Answers

You can use {#each ...}, like:

{#each Array(3) as _, i}
    <li>{i + 1}</li>
{/each}
like image 165
CD.. Avatar answered Oct 19 '22 13:10

CD..


An #each tag can loop anything with a length property, so:

{#each {length: 3} as _, i}
    <li>{i + 1}</li>
{/each}

will also work, if you prefer.

like image 89
Antony Jones Avatar answered Oct 19 '22 12:10

Antony Jones


i Use like this for travelling from a to b in Svelte

{#each Array.from(Array(b+1).keys()).slice(a) as i }
    <h1>{i}</h1>                    
{/each}

example (1 to 100):

{#each Array.from(Array(100+1).keys()).slice(1) as i }
    <h1>{i}</h1>                    
{/each}
like image 1
sk shahriar ahmed raka Avatar answered Oct 19 '22 13:10

sk shahriar ahmed raka