Vanilla JavaScript-Object.keys(Object.forEach)只显示最后一项

Vanilla JavaScript-Object.keys(Object.forEach)只显示最后一项,javascript,object,foreach,Javascript,Object,Foreach,我有一个遍历对象的函数 在HTML上,它应该在自己的表行中显示对象中的每个键和值 Object.keys(nutrients).forEach(function(key) { const nutrientsList = nutrients[key]; nutritionTable.innerHTML = `<tr> <td>${[ nutrientsList.label ]}<

我有一个遍历对象的函数

在HTML上,它应该在自己的表行中显示对象中的每个键和值

Object.keys(nutrients).forEach(function(key) {
    const nutrientsList = nutrients[key];

    nutritionTable.innerHTML = `<tr>
                                    <td>${[ nutrientsList.label ]}</td>
                                    <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td>
                                </tr>`
});
Object.keys(营养素).forEach(函数(键){
常量nutrientsList=营养素[关键];
nutritionTable.innerHTML=`
${[nutrientsList.label]}
${[nutrientsList.quantity]}${[nutrientsList.unit]}
`
});
当显示console.log时,它会按预期显示,但在HTML上会覆盖所有前面的元素,并且只显示最后一个元素


如何改进代码并获得正确的结果?

每次迭代都要替换整个HTML内容。我假设每次都要追加。要做到这一点,请使用


在每次迭代中,您都会更改nutriontable的
innerHTML
的值(因此您实际上会在循环中的每次迭代中重写该值,最终值是循环中最终迭代的值)

相反-您可以使用
+=
附加该值:

Object.keys(nutrients).forEach(function(key) {
    const nutrientsList = nutrients[key];

    nutritionTable.innerHTML += `<tr>
                                    <td>${[ nutrientsList.label ]}</td>
                                    <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td>
                                </tr>`
});
Object.keys(营养素).forEach(函数(键){
常量nutrientsList=营养素[关键];
nutriontable.innerHTML+=`
${[nutrientsList.label]}
${[nutrientsList.quantity]}${[nutrientsList.unit]}
`
});
  • x=y
    通过
    y
    覆盖
    x
    的值

  • x+=y
    (或
    x=x+y
    ):
    y
    值附加到
    x
    的当前值

然后:

nutriontable.innerHTML+=`..`//追加
for (const nutrientsList of Object.values(nutrients)) {
    nutritionTable.insertAdjacentHTML(
        "beforeend",
        `<tr>
             <td>${[ nutrientsList.label ]}</td>
             <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td>
        </tr>`);
}
Object.keys(nutrients).forEach(function(key) {
    const nutrientsList = nutrients[key];

    nutritionTable.innerHTML += `<tr>
                                    <td>${[ nutrientsList.label ]}</td>
                                    <td>${[ nutrientsList.quantity ]} ${[ nutrientsList.unit ]}</td>
                                </tr>`
});