gpt4 book ai didi

javascript - 遍历数组并根据计数添加到字符串

转载 作者:行者123 更新时间:2023-11-29 21:46:30 26 4
gpt4 key购买 nike

我试图遍历一个项目数组,并根据我们在数组中的计数构建一个 HTML 结构。

它应该将每个项目包装在一个单元格中,每 4 个项目包装在一行中,每 8 个项目包装在一个列 div 中。

这是 JavaScript:

var html = '';//对于那些询问 html 在哪里的人...

for(var i=0;i<response.length;i++)
{
// for first and every 8 items
if(i == 0 || i % 8 === 0)
{
console.log('columnstart');
html = html + '<div class="column">';
}

// for first and every 4 items
if(i == 0 || i % 5 === 0)
{
console.log('rowstart');
html = html + '<div class="row">';
}

// after every 4 items BUT NOT the first
if(i % 4 === 0 && i !== 0)
{
console.log('rowend');
html = html + '</div>';
}

// after every 8 items BUT NOT the first
if(i == response.length && i !== 0 || i % 7 === 0 && i !== 0)
{
console.log('columnend');
html = html + '</div>';
}

console.log('cell');
html = html + '<div class="cell"></div>';
}

下面是 HTML 应该如何呈现的示例:

<div class="column">
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>
<div class="column">
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
</div>
</div>

但是我的计数似乎不对...

因为我在控制台中得到以下信息:

columnstart
rowstart
cell
cell
cell
cell
cell
rowend
rowstart
cell
cell
cell
columnend
columnstart
cell
rowend
cell
rowstart
cell
cell

最佳答案

好吧,看来你的逻辑有很多错误,所以我只是重写了整个事情。基本上,将第一个和最后一个元素视为特殊情况,这样计数逻辑就不需要那么复杂。

查看评论了解更多信息:

var html = '';

for (var i = 0; i < response.length; i++) {
// If first element, open column and row and add first cell.
if (i == 0) {
html = html + '<div class="column">';
html = html + '<div class="row">';
html = html + '<div class="cell"></div>';

// If the first element, is also the last, then close row and column now.
if (i == response.length - 1) {
html = html + '</div>';
html = html + '</div>';
}
}
// If last element, add last cell and close row and column.
else if (i == response.length - 1) {
html = html + '<div class="cell"></div>';
html = html + '</div>';
html = html + '</div>';
}
// Otherwise, process based on count.
else {
// If end of row, then close row.
if (i % 4 == 0) {
html = html + '</div>';
}

// If end of column close column, open new column.
if (i % 8 == 0) {
html = html + '</div>';
html = html + '<div class="column">';
}

// If end of row, open new row.
if (i % 4 == 0) {
html = html + '<div class="row">';
}

// Insert the cell.
html = html + '<div class="cell"></div>';
}
}

Here is a working example

关于javascript - 遍历数组并根据计数添加到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31007897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com