-1

我正在练习模板字符串,我可以从简单的数组中获取数据,但如果你看到我在这里有多个信息,我想将它显示到表格中。我已经成功完成了for 循环(请参阅),但我想为此尝试 forEach。

const player_table = document.querySelector('.players');

const data =[
  {id:"uma"+815, name:"Ambar Jadhav", username:"ansurex", email:"ansurex@gmail.com"},
  {id:"umb"+822, name:"Meet Agarwal", username:"agarwalind", email:"meet.ind@yahoo.com"},
  {id:"umc"+830, name:"Omkar Kureshi", username:"kureshio", email:"omkara.re@gmail.com"},
  {id:"umd"+815, name:"Subodh Bhave", username:"subha01", email:"subh.drama@yahoo.com"}
];

let template = '';
for( let i = 0; i < data.length; i++ ){
  let info = data[i];
  template += `<tr><td> ${info.id} </td><td> ${info.name} </td><td> ${info.username}</td><td> ${info.email}</td></tr>`
} 

player_table.insertAdjacentHTML("beforeend",template)
4

1 回答 1

0

您可以使用Array.prototype.forEach, 它接受function带有 Array 项和 Array 项的索引的 a 作为参数。

 data.forEach(function(item, index){
   template += `<tr><td> ${item.id} </td><td> ${item.name} </td><td> ${item.username}</td><td> ${item.email}</td></tr>`;
 });

<table id="result"></table>
<script>
var template = "";
const data =[
{id:"uma"+815, name:"Ambar Jadhav", username:"ansurex", email:"ansurex@gmail.com"},
{id:"umb"+822, name:"Meet Agarwal", username:"agarwalind", email:"meet.ind@yahoo.com"},
{id:"umc"+830, name:"Omkar Kureshi", username:"kureshio", email:"omkara.re@gmail.com"},
{id:"umd"+815, name:"Subodh Bhave", username:"subha01", email:"subh.drama@yahoo.com"}
];
data.forEach(function(item, index){
       template += `<tr><td> ${item.id} </td><td> ${item.name} </td><td> ${item.username}</td><td> ${item.email}</td></tr>`;
     });
document.getElementById("result").innerHTML = template;
</script>

Array.prototype.reduce在这种情况下也可以使用(如stwilz建议的那样)。

 <table id="result"></table>
    <script>
    const data =[
    {id:"uma"+815, name:"Ambar Jadhav", username:"ansurex", email:"ansurex@gmail.com"},
    {id:"umb"+822, name:"Meet Agarwal", username:"agarwalind", email:"meet.ind@yahoo.com"},
    {id:"umc"+830, name:"Omkar Kureshi", username:"kureshio", email:"omkara.re@gmail.com"},
    {id:"umd"+815, name:"Subodh Bhave", username:"subha01", email:"subh.drama@yahoo.com"}
    ];
    const template = data.reduce((collection, item, index) => collection + `<tr><td> ${item.id} </td><td> ${item.name} </td><td> ${item.username}</td><td> ${item.email}</td></tr>`, '')
    document.getElementById("result").innerHTML = template;
    </script>

于 2018-07-23T21:53:35.800 回答