每个项目显示 4 行,其他剩余项目转到另一行

display 4 rows per items and other remained item go other row

<script>
    let cats = [
        { id: 'OUtn3pvWmp1', name: 'Cat1' },
        { id: 'OUtn3pvWmp2', name: 'Cat2' },
        { id: 'OUtn3pvWmp3', name: 'Cat3' },
        { id: 'OUtn3pvWmp4', name: 'Cat4' },
        { id: 'OUtn3pvWmp5', name: 'Cat4' },
        { id: 'OUtn3pvWmp6', name: 'Cat6' },
        { id: 'OUtn3pvWmp7', name: 'Cat7' },
      { id: 'OUtn3pvWmp8', name: 'Cat8' },
        { id: 'OUtn3pvWmp9', name: 'Cat9' },
        { id: 'OUtn3pvWmp10', name: 'Cat10' },
        { id: 'OUtn3pvWmp11', name: 'Cat11' },
        { id: 'OUtn3pvWmp12', name: 'Cat12' },
        
        //{ id: 'OUtn3pvWmp13', name: 'Cat13' },
    ];
</script>
<style>
.row {
display:grid;
grid-columns: 4;
}
 .card{
    background-color: gray !important;
    color: white;
    border-radius:10px;
    border-color: #404040;
      padding-left: 15px;
    padding-right: 15px;
  }
 
.card-group {
display: flex;
}
</style>

<h1>EXPECTED OUTPUT, BY LOOP OVER cats </h1>
{#each cats as cat, i}     
{#if i % 4 === 0}                   
<div class="row">         
    <div class="card-group">         
    <div class="card">{cats[i].name}</div>        
    <div class="card">{cats[i + 1].name}</div>      
    <div class="card">{cats[i + 2].name}</div>        
    <div class="card">{cats[i + 3].name}</div>                  
    </div>   
</div>                      
{/if} 
{/each}

我想 cat13 项目显示在另一行,任何人请给一些技巧。 我正在使用 sveltejs 3

我的可运行脚本here

我会用 cats 数组创建另一个数组。新数组将包含 sub-arrays 每个数组最多包含 4 个元素。

然后在 HTML 中,我们遍历新数组然后遍历子数组

/* divide your elements into another array where each index is a sub array array of 4 elements */
    let chunkit = (maxItems = 4) => {
        /* array to store the sub arrays of 4 elements */
        let chunks = [[]]
        /* iterate over the cats */
        for (let cat of cats) {
            /* if the last array of 4 elements has the length of 4, we create a new sub-array */
            if (chunks[chunks.length - 1].length == maxItems) {
                chunks.push([])
            }
            /* add the current element to the last sub array */
            chunks[chunks.length - 1].push(cat)
        }
        return chunks
    }

然后我们迭代函数chunkit

的return值
<div class="row">
    {#each chunkit() as fourCats}
        <div class="card-group">
            {#each fourCats as cat}
                <div class="card">{cat.name}</div>        
            {/each}
        </div>  
    {/each}
</div>

您可以将一个数字作为参数传递给函数maxItems来设置每个子类别中的元素数量

这里有一个例子repl