首页 > 解决方案 > 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 条目创建一个循环。提前感谢那些提供帮助的人。

标签: javascripthtmlarraysloops

解决方案


对于 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'];

我建议您对变量名使用驼峰式大小写


推荐阅读