gpt4 book ai didi

javascript - 如何将我的项目分成两组?

转载 作者:行者123 更新时间:2023-12-01 01:49:30 26 4
gpt4 key购买 nike

我想将一个项目数组拆分为左侧的两个项目和右侧的四个项目。

我的数组是:

// arrays of objects
const items = [
{ id: 1, title: "One" },
{ id: 2, title: "Two" },
{ id: 3, title: "Three" },
{ id: 4, title: "Four" },
{ id: 5, title: "Five" },
{ id: 6, title: "Six" },
];

// JS
document.write('<div class="row">');
document.write('<div class="left"><span>LEFT</span><br />');
items.map((a, b) => {
if (b % 2 == 0) {
document.write("</div><br />");
document.write(`<div class="right"><span>RIGHT</span><br />`);
document.write(`<span>${a.title}</span><br/>`);
} else {
document.write(`<span>${a.title}</span><br/>`);
}
});
document.write("</div>");
document.write("</div>");

我想要实现的输出是:

<div class="row">
<div class="left">
<div class="entry">
...content One...
</div>
<div class="entry">
...content Two...
</div>
</div>
<div class="right">
<div class="entry">
...content Three...
</div>
<div class="entry">
...content Four...
</div>
<div class="entry">
...content Five...
</div>
<div class="entry">
...content Six...
</div>
</div>
</div>

但是我得到了意想不到的输出:

LEFT

RIGHT
One
Two

RIGHT
Three
Four

RIGHT
Five
Six

请参阅JS Fiddle

欢迎任何帮助和建议。谢谢。

最佳答案

我认为这是一个简单的数学问题。你忘了 0/2 也是 0。:)

const lists = [
{
"id": 1,
"title": "One"
}, {
"id": 2,
"title": "Two"
}, {
"id": 3,
"title": "Three"
}, {
"id": 4,
"title": "Four"
}, {
"id": 5,
"title": "Five"
}, {
"id": 6,
"title": "Six"
}
];

document.write('<div class="row">')
document.write('<div class="left"><span>LEFT</span><br />')

// just to make sure right div write only once
write_div_once = true;

lists.map((a,b) => {
if((b+1)%3 == 0) { // here is the magic line. ;) Hope you will understand
if (write_div_once) {
write_div_once = false
document.write('</div><br />')
document.write(`<div class="right"><span>RIGHT</span><br />`)
}
document.write(`<span>${a.title}</span><br/>`)
} else{
document.write(`<span>${a.title}</span><br/>`)
}
});
document.write('</div>')
document.write('</div>')

关于javascript - 如何将我的项目分成两组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666061/

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