본문 바로가기
Framework/Svelte

[Svelte] 반복문 ( each )

by pcm9881 2023. 3. 22.

1.  임의 횟수 반복

<div>
    {#each Array(5) as _, i}
        <p>순서: {i}</p>
    {/each}
</div>

 

 

결과

 

 

2.  객체 배열 ( Array of Objects )

<script>
    const list = [
        { name: "홍길동", age: 30 },
        { name: "임꺽정", age: 31 },
        { name: "김춘삼", age: 32 },
    ];
</script>

<div>
    {#each list as item, i}
        <p>index: {i}. name: {item.name}, age: {item["age"]}</p>
    {/each}
</div>

결과

 

 

3. 객체 배열 ( Array of Objects ) Key 지정

key를 지정하는 이유는 svelte에서 key를 활용해서 데이터변경시 다시 렌더링을 합니다.

<script>
    const list = [
        { id: "11", name: "홍길동", age: 30 },
        { id: "44", name: "임꺽정", age: 31 },
        { id: "33", name: "김춘삼", age: 32 },
        { id: "22", name: "김개똥", age: 33 },
        { id: "23", name: "김숙", age: 33 },
    ];
</script>

<div>
    {#each list as item, i (item.id)}
        <p>index: {i}. name: {item.name} age: {item["age"]}</p>
    {/each}
</div>

결과

 

 

참조

[svelte tutorial each-blocks]: https://svelte.dev/tutorial/each-blocks

 

Logic / Each blocks • Svelte Tutorial

Logic / Each blocks a. Basicsb. Adding datac. Dynamic attributesd. Stylinge. Nested componentsf. Making an appa. Assignmentsb. Declarationsc. Statementsd. Updating arrays and objectsa. Declaring propsb. Default valuesc. Spread propsa. If blocksb. Else bloc

svelte.dev

[svelte tutorial keyed-each-blocks]: https://svelte.dev/tutorial/keyed-each-blocks

 

Logic / Keyed each blocks • Svelte Tutorial

Logic / Keyed each blocks a. Basicsb. Adding datac. Dynamic attributesd. Stylinge. Nested componentsf. Making an appa. Assignmentsb. Declarationsc. Statementsd. Updating arrays and objectsa. Declaring propsb. Default valuesc. Spread propsa. If blocksb. Els

svelte.dev

 

728x90

댓글