您将如何将此for循环转换为foreach?这是我正在练习模板字符串的代码

时间:2018-07-23 21:45:11

标签: javascript arrays foreach ecmascript-6 template-strings

我正在练习模板字符串,我可以从简单数组中获取数据,但是如果您看到这里有多个信息,我想将其显示在表中。我已经成功完成了for loop(请参阅),但是我想为此尝试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)

1 个答案:

答案 0 :(得分:0)

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

 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>