javascript - JS循环基于数组中的数据数量
问题描述
我想在 JS 中创建一个循环,为我的数组上的每个“id”创建一个 div。例如,我有以下内容:
var Boletins =
{
id:1, items:
[
{
"#": "1",
"Data": "19 a 25 de Março de 2021",
"Região": "região de Trás-Os-Montes e Alto Douro",
"Niveis": "muito elevados",
"PoleneArvore": "cipreste, pinheiro",
"PoleneErva": "urtiga, gramíneas"
}],
id:2, items:
[
{
"#": "10",
"Data": "26 de Março a 1 de Abril de 2021",
"Região": "região de Trás-Os-Montes e Alto Douro",
"Niveis": "muito elevados",
"PoleneArvore": "plátano, cipreste, pinheiro, carvalhos"
}
]
}
基于 id,我想创建一个循环,为数组上存在的每个“id”条目在 HTML 中创建一个 Div。在我的代码中它到达 id:14 但我只粘贴到 id:2。这是我创建 div 的代码:
htmlText += '<div class="divBoletim">';
htmlText += '<p>Created Div</p>';
htmlText += '</div>';
$('body').append(htmlText);
我只是不明白如何为每个 id 条目创建一个循环。提前感谢那些提供帮助的人。
解决方案
对于 js,您不能对 object 使用该结构,Boletins
对于每个对象,您只能使用一个带有 nameid
的属性和一个带有 name 的属性items
。如果您使用您在代码中向我们展示的结构,该对象Boletins
将仅包含一个属性id
(值为 2)和一个属性items
。要根据需要循环,您需要使用数组:
const boletins = [{
id: 1,
data: '19 a 25 de Março de 2021',
...
}, {
id: 2,
data: '...',
...
}];
一旦你用这段代码定义了数组,你就可以有一个for
循环:
for (let i=0; i<boletins.length; i++) {
const item = boletins[i];
console.log(item.data); // first way to get the info you need
console.log(item['data']); // second way
// do something
}
或使用forEach
循环:
boletins.forEach(item => {
console.log(item.data);
console.log(item['data']);
// do something.
});
您还可以使用以下方法直接访问元素:
const firstData = boletins[0].data;
const secondPoleneErva = boletins[1]['PoleneErva'];
我建议您对变量名使用驼峰式大小写。
推荐阅读
- javascript - 进入房间时扔进另一个房间
- python - 当我运行我的 python 脚本时,其中使用的 jpg 文件变为 jpg.REMOVE_ME。我能做些什么?
- python - 在 KIVY 应用程序 ResultIntent 中将数据作为 PutExtras 传递
- django - django-rest-framework 获取自通过序列化创建对象以来的时间戳
- python - 如何在 Python 中使用 openpyxl 遍历每一行并同时插入行?
- python - Pandas,基于两个标签删除重复项的最安全方法,保留第三个标签得分最高的行
- python - 使用 pytorch 实现预训练的 BETO 模型(bert 的西班牙语版本)时出错
- for-loop - 如何使用批处理多行的txt文件对所有mp4文件运行命令
- elasticsearch - Elasticsearch:如何使用无痛从 post_filter 访问嵌套字段
- c++ - 我的 seconds 变量没有正确存储