In this article I will show how to loop each block on provided length. This could be done by using either the Array() function or length property.

Using Array() –

var superhero = ["Ironman", "Thor", "Hulk"]

{#each Array(3) as _, i}
    <li>{superhero[i]}</li>
{/each}

Using Length property –

var superhero = ["Ironman", "Thor", "Hulk"]

{#each {length: 3} as _, i}
    <li>{superhero[i]}</li>
{/each}

If you want to dynamically update the list with increase in element count, then use this code –

<script>
	let count = 3;
</script>

<button on:click={() => count = count + 1 }>+</button>
<button disabled={count === 1} on:click={() => count = count - 1 }>-</button>

{#each Array(count) as _, i}
    <li>{i + 1}</li>
{/each}

    Tweet this to help others

Live Demo

Tagged in:

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles