遍历对象数组,并将其转换为UL中的LI项

时间:2019-02-05 16:13:49

标签: javascript html

<div id="dataTable">
    <button onclick="show()">Print data</button>

    <ul id="hcplist">

    </ul>
</div>

我需要遍历

let hcpdata = [{ "name": "David", "hcp": 54 }, { "name": "Jack", "hcp": 5 }, { "name": "Hanna", "hcp": 20 }];

在该循环中制作<li>个项目,并在没有jQuery或其他库的<ul>hcplist)中输出-诸如“ David 54”,“ Jack 5”等项目。

2 个答案:

答案 0 :(得分:-1)

let hcpdata = [{ "name": "David", "hcp": 54 }, { "name": "Jack", "hcp": 5 }, { "name": "Hanna", "hcp": 20 }];

function show() {
  let list = document.getElementById("hcplist");
  hcpdata.forEach((d) => {
    let el = "<li>"+ d.name + " " + d.hcp+"</li>";
    list.innerHTML += el;
  });
}
<div id="dataTable">
    <button onclick="show()">Print data</button>

    <ul id="hcplist">

    </ul>
</div>

答案 1 :(得分:-1)

使用此功能

  function show()
    {
      let hcpdata = [{ "name": "David", "hcp": 54 }, { "name": "Jack", "hcp": 5 }, { "name": "Hanna", "hcp": 20 }];
    let html='';
    for( let i=0;hecpdata.length;i++){
       html+='<li>'+hecpdata[i].name + ' ' + hecpdata[i].hcp+'</li>'; 
    }
     document.getElementById('hcplist').innerHTML=html;
    }